之前在使用大前端的 DUX 主题时,感觉该主题的文章内容折叠功能非常的实用,一直想移植到现在使用的主题下。该功能对于优化文章结构还是非常有用的。可以将文章中某些不是很重要的内容隐藏起来,读者可以根据需要决定是否展开折叠的内容。从而使得文章内容更加简洁有条理性。点击下方按钮查看效果:
下面上干货:
代码来自于: 钻芒博客
一、引用 js 文件,将以下代码加入至主题目录下的 footer.php 中
如果网站已经引用了 jquery.js 文件,可删除第一行代码。
注意 jquery.js 引用的版本在 3.4.1 以下可能会无法正常使用。
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<script>
jQuery(document).ready(
function(jQuery){
jQuery('.collapseButton').click(function(){
jQuery(this).parent().parent().find('.xContent').slideToggle('slow');
});
});
</script>
二、将下方代码添加至主题目录下的 functions.php 中
可根据自己的喜好修改样式文件
// 文章页添加展开收缩效果
function xcollapse($atts, $content = null){
extract(shortcode_atts(array("title"=>""),$atts));
return '
<style>.xControl {
font-size: 15px;
font-weight: bold;
padding: 5px 0;
box-shadow:0 0 20px #d0d0d0;/* 阴影 */
background-color: #FFFFFF;/* 背景颜色 */
border-bottom: 2px solid #e74c3c;/* 边 */
transition: all 0.1s linear;
text-align: center;
border-radius: 0 0 5% 5%;
border-radius:4px;
}
.xControl a{
text-decoration: none;
display: block;}
.xControl a:hover {
text-decoration: none;
display: block;
color:red;
}
.xControl i{font-style:normal;}
</style>
<div style="margin: 0.5em 0;">
<div class="xControl">
<a href="javascript:void(0)" class="collapseButton xButton"> <i class="fa fa-toggle-on" aria-hidden="true"> </i><span class="xTitle">'.$title.'</span></a>
<div style="clear: both;"></div>
</div>
<div class="xContent" style="display: none;">'.$content.'</div>
</div>';
}
add_shortcode('collapse', 'xcollapse');
三、给文章编辑添加展开/收缩快捷标签按钮
将以下代码添加到主题目录下的 functions.php 文件中
//添加展开/收缩快捷标签按钮
function appthemes_add_collapse() {
?>
<script type="text/javascript">
if ( typeof QTags != 'undefined' ) {
QTags.addButton( 'collapse', '展开/收缩按钮', '[collapse title="点击展开 查看更多"]','[/collapse]' );
}
</script>
<?php
}
add_action('admin_print_footer_scripts', 'appthemes_add_collapse' );
使用方法;
在文章编辑器中选择文本,单击展开/收缩按钮,输入要折叠的内容,然后再次点击展开/收缩按钮。会自动添加折叠结束标签。如下图所示:
我也为我的博客添加上这个功能,非常感谢分享。
能帮助到大家就好