一、效果演示
二、代码教程
1.function.php文件代码法创建文章目录功能
// 设置文章目录 function create_mg($html) { $mg = ''; if (is_single()) { if (!$html) return $html; $dom = new DOMDocument(); libxml_use_internal_errors(true); $dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8')); libxml_clear_errors(); $mg = ''; $html = $dom->saveHTML(); } return $mg . $html;//在目录中的每个标题前添加项目符号。 } add_filter('the_content', 'create_mg');目录
';//向目录添加标题并将其显示在此之上。您可以将文本“目录”替换为您希望在标题中出现的任何内容。 $h2_status = 0; $h3_status = 0; $i = 1; foreach($dom->getElementsByTagName('*') as $element) { if($element->tagName == 'h2') { if($h3_status){ $mg .= '
'; $h3_status = 0; } if($h2_status){ $mg .= ''; $h2_status = 0; } $h2_status = 1; $mg .= '' . $element->textContent . '';//单击后立即创建指向文章中相应部分的跳转链接。 $element->setAttribute('id', 'mg-' . $i); $i++; }elseif($element->tagName == 'h3') { if(!$h3_status){ $mg .= ' '; } $mg .= ''; $h3_status = 1; } $mg .= '
'; } if($h2_status){ $mg .= '- ' . $element->textContent . '
'; $element->setAttribute('id', 'mg-' . $i); $i++; } } if($h3_status){ $mg .= '
2.style.css美化文章目录
/*文章目录-www.287587.com*/.mg-bound { height: 108px; box-shadow: 0 2px 8px rgb(0 0 0 / 10%); color: #fff; position: fixed; left: 0; font-size: 14px; text-align: center; z-index: 999999; } .mg-bound__hover-block{ border: none !important; position: absolute !important; left: 0; z-index: 100; padding: 0 !important; width: 40px; height: 108px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; color: #fff; background-color: #515151; } .mg-bound__hover-block i{ margin-top: 10px; display: block; font-size: 22px; } .mg-bound__hover-block p{ width: 28px; margin-left: 6px; font-size: 16px; text-align: center; } .mg-bound__popover{ position: absolute !important; left: 0; top: 0; width: 200px !important; min-height: 108px !important; padding: 8px !important; padding-left: 45px !important; border-top-right-radius: 10px; border-bottom-right-radius: 10px; overflow: hidden; border-bottom: none !important; transform: translateX(-200px); -ms-transform: translateX(-200px); -webkit-transform: translateX(-200px); transition: all .3s; background-color: #515151; text-align: left; font-size: 12px; } .mg-bound__popover li { border-left: 3px solid #fff; padding: 6px; } .mg-bound:hover .mg-bound__popover{ display: block; transform: translateX(0); -ms-transform: translateX(0); -webkit-transform: translateX(0); transition: all .3s; } .entry-content a, .entry-content .content-show-roles > p a, .entry-content > ul li a, .content-show-roles > li a, .entry-content > ol li a { color: #ffffff; }