为博客园markdown代码块添加折叠

引言:

当我们在文章某段代码中写太多内容时,进行适当的内容折叠是非常有必要的。

请尝试点击一下Code👇

Show Code
int found(int a[],int left,int right,int x) {
	while (left < right) {
		int mid = (right + left) >> 1;
		if (a[mid] < x) left = mid + 1;
		else right = mid;
	}
	return left;
}

点开上面的Code就出现折叠的代码是不是很有意思?

其实实现这个功能的原理很简单、利用HTML的知识短短几行即可完成。

update 19/04/21

<details> 
<summary><font size="4" color="orange">Show Code</font></summary> 
<pre><code class="language-cpp">这里填充代码</code>
</pre> </details>

下面这个是老版本样式

<details>
<summary>Code</summary>
<pre><code class="language-cpp">
被折叠的代码块或者文章内容,内部不可以有空行
</code></pre>
</details>

利用上方的HTML样式即可轻松完成代码在markdown中实现折叠

核心是利用 datails 标签描述文档或文档某个部分的细节。

与<summary>标签 配合使用可以为 details 定义标题。标题是可见的,用户点击标题时,会显示出 details。

好了,理解本质以后再看看最开始的 Code中的所有代码吧

<details>
<summary>Code</summary>
<pre><code class="language-cpp">int found(int a[], int left, int right, int x) {
    while (left < right) {
        int mid = (right + left) >> 1;
        if (a[mid] < x) left = mid + 1;
        else
            right = mid;
    }
    return left;
}
</code></pre>
</details>

注意事项:

对于 <>的特殊符号应该用 &lt; &gt; 代替,不然会显示错误。(只需要修改 < 替换为 &lt; 即可)

<code>必须紧贴代码开头(避免多出首行),</code>需单独一行(避免少了尾行)

动态演示图来自网络


折叠代码样式更新 (填充代码至Code标签即可)

<details class="custom-block details" style="display: block; position: relative; border-radius: 2px; margin: 1.6em 0px; padding: 1.6em; background-color: rgb(238, 238, 238); color: rgb(44, 62, 80); font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, Roboto, Oxygen, Ubuntu, Cantarell, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; font-size: 16px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;"><summary style="outline: none; cursor: pointer;">Code (C++)</summary><pre><code class="language-cpp">代码放置区</code></pre></details>

实际样式

Code (C++)
代码放置区

参考:

https://www.w3school.com.cn/tags/tag_details.asp

posted @ 2020-10-16 20:22  RioTian  阅读(3604)  评论(7编辑  收藏  举报