wordpress中mac风格代码高亮显示

依赖highlight.jsjQuery

1.将文件上传至wordpress/wp-content/themes并解压

2.编辑主题文件header.php,引入css和js

<!DOCTYPE html>
<html>
    <head>
        <!-- 引入样式文件,根据自己需求修改 -->
        <link rel="stylesheet" 
            href="/wp-content/themes/highlight/styles/monokai_sublime.css"
            type="text/css" >
        <!-- 引入js文件 -->
        <script src="/wp-content/themes/highlight/highlight.pack.js" 
            type="text/javascript" ></script>
        <!-- 引入jQuery -->
        <script src="/wp-content/themes/jquery/dist/jquery.js" 
            type="text/javascript" ></script>
        <!-- mac风格头部 -->
        <style>
            .hljs .tools{
                float: left;
                margin: 5px 5px 6px 5px ;
                width: 10px;height: 10px;
                border-radius: 5px;
                text-align: center;
                line-height: 10px;
            }
        </style>
        <!-- 运行highlight.js -->
        <script>hljs.initHighlightingOnLoad();</script>
    </head>
<body>
</body>
</html>

3. 使用jQuery改变<pre><code></code></pre>样式,编辑footer.php

<script type="text/javascript">
//手字母大写
function titleCase(str) {
    let strArr = str.split(' ');
    for(let i=0;i<strArr.length;i++){
        strArr[i] = strArr[i].substring(0,1).toUpperCase()
          + strArr[i].toLowerCase().substring(1)
    } 
    return strArr.join(' ');
} 
jQuery(function ($) {
    $("pre code").each(function(){
        var lines = $(this).text().split('\n').length ;
	var codename =titleCase($(this).attr("class").split(" ")[2]);
	var str ="<div class='hljs' style='border-top-left-radius: 
            5px;border-top-right-radius: 8px;padding: 3px'>" +
            "<div class='tools' style='background-color: red'></div>" +
            "<div class='tools' style='background-color: yellow'></div>" +
            "<div class='tools' style='background-color:green'></div>" +
	    codename + "</div>";
	console.log(str);
	$(this).parent().prepend(str);
	$(this).css('padding-top','0');
	$(this).css('opacity','0.95');
    });
});
</script>
This entry was posted in wordpress. Bookmark the permalink.

发表回复