喜迎
元旦

Hexo博客主题安装以及优化(二)


Matery主题个性化

动态标题

打开博客主题文件夹,路径:themes/matery/layout/layout.ejs,在对应位置添加如下代码:


<script type="text/javascript">
var OriginTitile = document.title,
    st;
document.addEventListener("visibilitychange", function () {
    document.hidden ? (document.title = "写离开页面标题显示的内容", clearTimeout(st)) : (document.title =
        "写进入页面标题显示的内容", st = setTimeout(function () {
            document.title = OriginTitile
        }, 3e3))
})

修改导航栏颜色以及透明效果

打开themes/matery/source/css/matery.css文件,大约在250行,有一个.bg-color属性,修改其属性值即可,代码如下:

    .bg-color {
    background-image: linear-gradient(to right, #4cbf30 0%, #0f9d58 100%); //修改成自己喜欢的颜色值
    opacity: 0.8;  //透明效果 值范围 0~1,看情况自己修改
    }

添加动态诗词

采用的是今日诗词,每次返回一句诗词,根据时间、地点、天气、事件智能推荐。官网有API文档,可以去看一下,有多种安装方式,最简单的方式就是从官网获取代码,在/themes/matery/layout/_partial/head.ejs添加下面的一行代码:


<script src="https://sdk.jinrishici.com/v2/browser/jinrishici.js" charset="utf-8"></script>

鼠标点击文字特效

实现方法,引入js文件,在主题文件下的/source/js/下新建click_show_text.js,其代码如下:

    var a_idx = 0;
    jQuery(document).ready(function ($) {
    $("body").click(function (e) {
        var a = new Array("富强", "民主", "文明", "和谐", "自由", "平等", "公正", "法治", "爱国", "敬业", "诚信", "友善");
        var $i = $("<span/>").text(a[a_idx]);
        a_idx = (a_idx + 1) % a.length;
        var x = e.pageX,
            y = e.pageY;
        $i.css({
            "z-index": 5,
            "top": y - 20,
            "left": x,
            "position": "absolute",
            "font-weight": "bold",
            "color": "#FF0000"
        });
        $("body").append($i);
        $i.animate({
                "top": y - 180,
                "opacity": 0
            },
            3000,
            function () {
                $i.remove();
            });
    });
    setTimeout('delay()', 2000);
    });

    function delay() {
    $(".buryit").removeAttr("onclick");
    }

添加背景壁纸

在matery.css文件下查找body样式,修改如下:

    body { 
        /* background-color: #eaeaea; */ 
        background: linear-gradient(60deg, rgba(255, 165, 150, 0.5) 5%, rgba(0, 228, 255, 0.35) ) 0% 0% / cover, url("https://x.png"), url("https://x.jpg") 0px 0px; 
        background-attachment: fixed; 
        margin: 0; 
        color: #7F95D1; 
     }

如果不想要图片,去掉即可,比如:

    body { 
    cursor:url(/cursor.svg),auto; 
    background: linear-gradient(60deg, rgba(255, 165, 150, 0.5) 5%, rgba(0, 228, 255, 0.35) ); 
    margin: 0; 
    color: #34495e; 
    }

修改滑动条

在matery.css中添加样式即可:

    /* 滚动条 */ 
    ::-webkit-scrollbar-thumb { 
        background-color: #FF2A68; 
        background-image: -webkit-linear-gradient(45deg,rgba(255,255,255,.4) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.4) 50%,rgba(255,255,255,.4) 75%,transparent 75%,transparent); 
        border-radius: 3em; 
    } 
    ::-webkit-scrollbar-track {
        background-color: #ffcacaff; 
        border-radius: 3em; 
    } 
    ::-webkit-scrollbar { 
        width: 8px; 
        height: 15px; 
    }

添加天气小插件

首先去中国天气官网配置自己的插件,选择自定义插件—>自定义样式——>生成代码,然后会生成一段代码,复制粘贴到themes/matery/layout/layout.ejs即可。

关于我页面添加个人简历

打开theme/matery/layout/about.ejs文件,大约在13行。有一个``标签,找出其对应结尾的标签,大约在61行左右,然后在新增如下代码:

    <div class="card">
     <div class="card-content">
         <div class="card-content article-card-content">
             <div class="title center-align" data-aos="zoom-in-up">
                 <i class="fa fa-address-book"></i>&nbsp;&nbsp;<%- __('个人简历') %>
              </div>
                 <div id="articleContent" data-aos="fade-up">
                     <%- page.content %>
                 </div>
           </div>
      </div>
    </div>

注意:

粘贴的位置和空格要正确,这里的位置随你自己设置,你也可以把简历作为第一个card,然后/source/about/index.md下面写上你的简历了(就像写博客一样)。

修改原有相册

请参考我这位朋友的教程

博主同款相册请参考这篇文章

豆瓣书单电影页面

首先在博客站点目录执行下面的命令安装豆瓣插件:


npm install hexo-douban --save

紧接着在博客站点目录的配置文件_config.yml下,添加如下配置:


douban: 
  user: 252345665    #这个需要修改为你个人的id  
  builtin: false   #如果想生成豆瓣页面,这个需要设置为true
  book: 
      title: 'This is my book title' 
      quote: 'This is my book quote' 
 movie: 
     title: 'This is my movie title' 
     quote: 'This is my movie quote' 
 game: 
     title: 'This is my game title' 
     quote: 'This is my game quote' 
 timeout: 10000

user::你的豆瓣ID。打开豆瓣,登入账户,然后在右上角点击 ”个人主页“,这时候地址栏的URL大概是这样:https://www.douban.com/people/xxxxxx/ ,其中的”xxxxxx”就是你的个人ID了。

builtin:是否将生成页面的功能嵌入 hexo s 和 hexo g 中,默认是 false ,另一可选项为 true 。

title: 该页面的标题。

quote: 写在页面开头的一段话,支持html语法。

timeout: 爬取数据的超时时间,默认是 10000ms,如果在使用时发现报了超时的错(ETIMEOUT)可以把这个数据设置的大一点。

如果只想显示某一个页面(比如movie),那就把其他的配置项注释掉即可。

然后再主题配置文件_config.yml中添加关于此页面的菜单:


menu:
    媒体:
       url: /
       icon: fas fa-list
       children:
         - name: 电影
           url: /movies
           icon: fas fa-film
         - name: 书单
           url: /books
           icon: fas fa-book
         - name: 游戏
           url: /games
           icon: fas fa-gamepad

适配Matery主题:在 /themes/hexo-theme-matery/layout 文件夹下面创建一个名为 douban.ejs 的文件,并将下面的内容复制进去:

    <%- partial('_partial/post-cover') %> 
    <style> 
        .hexo-douban-picture img {
        width: 100%; 
        } 
    </style>
    <main class="content"> 
    <div id="contact" class="container chip-container"> 
        <div class="card"> 
            <div class="card-content" style="padding: 30px"> 
                <h1 style="margin: 10px 0 10px 0px;"><%= page.title %></h1> 
                <%- page.content %> 
            </div> 
        </div> 
        <div class="card"> 
            <div class="card-content" style="text-align: center"> 
                <h3 style="margin: 5px 0 5px 5px;">如果你有好的内容推荐,欢迎在下面留言!</h3> 
            </div> 
        </div> 
        <div class="card"> 
            <% if (theme.gitalk && theme.gitalk.enable) { %>
                <%- partial('_partial/gitalk') %>
            <% } %> 
            <% if (theme.gitment.enable) { %> 
                <%- partial('_partial/gitment') %> 
            <% } %> 
            <% if (theme.disqus.enable) { %> 
                <%- partial('_partial/disqus') %> 
            <% } %> 
            <% if (theme.livere && theme.livere.enable) { %> 
                <%- partial('_partial/livere') %> 
            <% } %> 
            <% if (theme.valine && theme.valine.enable) { %> 
                <%- partial('_partial/valine') %> 
            <% } %> 
        </div> 
    </div> 
    </main>

然后在博客站点目录下的node_modules文件夹下找到hexo-douban/lib,文件夹下有三个js文件,分别为:books-generator.js 、games-generator.js 、movies-generator.js,用文本编辑器打开这三个文件,并将其文件内容末尾的代码修改为一下内容:


/* 原文件内容为 layout: [`page`, `post`] ,将其修改为下面的内容*/
layout: [`page`, `douban`]

最后就是使用并生成相应的页面,执行命令如下:


hexo douban

需要注意的是,通常大家都喜欢用 hexo d 来作为 hexo deploy 命令的简化,但是当安装了 hexo douban 之后,就不能用 hexo d 了,因为 hexo douban 跟 hexo deploy 的前缀都是 hexo d ,你以后执行的 hexo d 将不再是 Hexo 页面的生成,而是豆瓣页面的生成。

以下是可选的命令参数:


-h, --help    # 帮助页面
-b, --books   # 只生成书单页面
-g, --games   # 只生成游戏页面
-m, --movies  # 只生成电影页面

当站点配置文件的builtin的值为true时,生成页面的功能会嵌入到hexo g和hexo s中,在进行部署生成操作,会自动生成相应的页面。

外链跳转插件

hexo-external-link是一个跳转外链相关插件。自动为所有html文件中外链的a标签生成对应的属性。 比如 设置target=’_blank’, rel=’external nofollow noopener noreferrer’ 告诉搜索引擎这是外部链接,不要将该链接计入权重。 同时自动生成外链跳转页面,默认在根目录下 go.html;

使用 npm 或者 yarn 安装:


## npm 安装
npm install hexo-external-link --save
## yarn 安装
yarn add hexo-external-link

之后再hexo博客站点根目录下添加如下配置:


hexo_external_link:
  enable: true
  enable_base64_encode: true
  url_param_name: 'u'
  html_file_name: 'go.html'
  target_blank: true
  link_rel: 'external nofollow noopener noreferrer'
  domain: 'your_domain' # 如果开启了防盗链,填写你的域名
  safety_chain: true

enable - 是否开启hexo_external_link插件 - 默认 false

enable_base64_encode - 是否对跳转url使用base64编码 - 默认 fasle

url_param_name - url参数名,在跳转到外链传递给html_file_name的参数名 - 默认 ‘u’

html_file_name - 跳转到外链的页面文件路径 - 默认 ‘go.html’

target_blank - 是否为外链的a标签添加target=’_blank’ - 默认 true

link_rel - 设置外链的a标签的rel属性 - 默认 ‘external nofollow noopener noreferrer’

domain - 如果开启了防盗链,除了 localhost 和 domain(你的域名) 之外调用会跳到主页,同时也是判断链接是否为外链的依据 - 默认 window.location.host

safety_chain - go.html 为了防止外链盗用 对域名进行的判断 - 默认 false
添加动态科技线条背景,在主题配置文件(_config.yml)激活即可。

添加鼠标点击烟花爆炸效果

首先在themes/matery/source/js目录下新建fireworks.js文件,打开这个网址,将内容复制粘贴到新建的fireworks.js即可。

然后再themes/matery/layout/layout.ejs文件内添加下面的内容:

    <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;" ></canvas> 
    <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
    <script type="text/javascript" src="/js/fireworks.js"></script>

然后


hexo clean && hexo g && hexo s

即可,就可以看到效果了。

添加樱花飘落效果

在themes/matery/source/js目录下新建sakura.js文件,打开这个网址,将内容复制粘贴到新建的sakura.js即可。

然后再themes/matery/layout/layout.ejs文件内添加下面的内容:


<script src="/js/sakura.js"></script>

然后


hexo clean && hexo g && hexo s

即可,就可以看到效果了。

添加雪花飘落效果

在themes/matery/source/js目录下新建snow.js文件,打开这个网址,将内容复制粘贴到新建的snow.js即可。

然后再themes/matery/layout/layout.ejs文件内添加下面的内容:


<script src="/js/snow.js"></script>

然后


hexo clean && hexo g && hexo s

即可,就可以看到效果了。

添加鼠标彩虹星星掉落跟随效果

在themes/matery/source/js目录下新建cursor.js文件,打开这个网址传送门,将内容复制粘贴到新建的cursor.js即可。

然后再themes/matery/layout/layout.ejs文件内添加下面的内容:


<script src="/js/cursor.js"></script>

然后


hexo clean && hexo g && hexo s

即可,就可以看到效果了。

文章生成永久链接

主题默认的文章链接配置是:


permalink: :year/:month/:day/:title

这种生成的链接地址很长,文章版权的链接地址会出现一大串字符编码,一点也不好看。因此需要修改文章生成链接的格式。

首先再根目录下执行下面的命令:


npm install hexo-abbrlink --save

然后再站点配置文件下添加如下配置:


abbrlink:
alg: crc16   #算法: crc16(default) and crc32
rep: hex     #进制: dec(default) and hex: dec #输出进制:十进制和十六进制,默认为10进制。丨dec为十进制,hex为十六进制

再将站点配置文件的permalink的值修改为:


permalink: posts/:abbrlink.html  # 此处可以自己设置,也可以直接使用 :/abbrlink

生成完后,原md文件的Front-matter 内会增加abbrlink 字段,值为生成的ID 。这个字段确保了在我们修改了Front-matter 内的博客标题title或创建日期date字段之后而不会改变链接地址。

添加评论系统

添加来必力评论系统

首先去来必力官网,点击导航栏上的安装。

City 版:是一款适合所有人使用的免费版本;
Premium 版:是一款能够帮助企业实现自动化管理的多功能收费版本。注册完之后,会提示你填写网站的相关信息,如网站链接,网站名称等等,填写完毕之后,会给你一段代码。

到主题配置文件里找到:


# Livere comment configuration, the default is not activated
# Livere 来必力评论模块的配置,默认为不激活

livere:
enable: true # true即为开启评论系统
uid: #这里填写你的uid
然后


hexo clean && hexo g && hexo s

即可,就可以看到效果了。

添加Valine评论系统

注册LeanCloud,经过登录或者注册之后再登录,就会进入如下的页面:

创建应用完成后,会出现如下页面,然后点击设置

会出现下面的页面,将其中APPID和APPKey复制,添加到配置文件(_config.yml)中。


# The configuration of the Valine comment module is not activated by default.
# To use it, activate the configuration item and set appId and appKey.
# Valine 评论模块的配置,默认为不激活,如要使用,就请激活该配置项,并设置 appId 和 appKey.
valine:
  enable: false  # true即为开启评论系统
  appId:   #此处填写你的appid
  appKey:  #此处填写你的appkey
  notify: false
  verify: false
  visitor: true
  avatar: 'mm' # Gravatar style : mm/identicon/monsterid/wavatar/retro/hide
  pageSize: 10
  placeholder: 'just go go' # Comment Box placeholder
  background:  https://mx142.cn//medias/comment_bg.png

然后


hexo clean && hexo g && hexo s

即可,就可以看到效果了。

图片懒加载

安装插件:hexo-lazyload-image
在站点根目录执行下面的命令:


npm install hexo-lazyload-image --save

之后在站点配置文件下添加下面的代码:


lazyload:
  enable: true  # 是否开启图片懒加载
  onlypost: false  # 是否只对文章的图片做懒加载
  loadingImg: # eg ./images/loading.gif

然后


hexo clean && hexo g && hexo s

即可,就可以看到效果了。

代码压缩

gulp代码压缩

进入站点根目录下依次执行下面的命令:


# 全局安装gulp模块
npm install gulp -g
# 安装各种小功能模块  执行这步的时候,可能会提示权限的问题,最好以管理员模式执行
npm install gulp gulp-htmlclean gulp-htmlmin gulp-minify-css gulp-uglify gulp-imagemin --save
# 额外的功能模块
npm install gulp-debug gulp-clean-css gulp-changed gulp-if gulp-plumber gulp-babel babel-preset-es2015 del @babel/core --save

在Hexo根目录新建文件 gulpfile.js,并复制以下内容到文件中,有中文注释,可以根据自己需求修改。(注意:文件名不能错,一定为gulpfile.js,否则会出错!)

    var gulp = require("gulp");
    var debug = require("gulp-debug");
    var cleancss = require("gulp-clean-css"); //css压缩组件
    var uglify = require("gulp-uglify"); //js压缩组件
    var htmlmin = require("gulp-htmlmin"); //html压缩组件
    var htmlclean = require("gulp-htmlclean"); //html清理组件
    var imagemin = require("gulp-imagemin"); //图片压缩组件
    var changed = require("gulp-changed"); //文件更改校验组件
    var gulpif = require("gulp-if"); //任务 帮助调用组件
    var plumber = require("gulp-plumber"); //容错组件(发生错误不跳出任务,并报出错误内容)
    var isScriptAll = true; //是否处理所有文件,(true|处理所有文件)(false|只处理有更改的文件)
    var isDebug = true; //是否调试显示 编译通过的文件
    var gulpBabel = require("gulp-babel");
    var es2015Preset = require("babel-preset-es2015");
    var del = require("del");
    var Hexo = require("hexo");
    var hexo = new Hexo(process.cwd(), {}); // 初始化一个hexo对象

    // 清除public文件夹
    gulp.task("clean", function () {
        return del(["public/**/*"]);
    });

    // 下面几个跟hexo有关的操作,主要通过hexo.call()去执行,注意return
    // 创建静态页面 (等同 hexo generate)
    gulp.task("generate", function () {
    return hexo.init().then(function () {
        return hexo
            .call("generate", {
                watch: false
            })
            .then(function () {
                return hexo.exit();
            })
            .catch(function (err) {
                return hexo.exit(err);
            });
        });
    });

    // 启动Hexo服务器
    gulp.task("server", function () {
        return hexo
            .init()
            .then(function () {
                return hexo.call("server", {});
        })
        .catch(function (err) {
            console.log(err);
        });
    });

    // 部署到服务器
    gulp.task("deploy", function () {
        return hexo.init().then(function () {
            return hexo
            .call("deploy", {
                watch: false
            })
            .then(function () {
                return hexo.exit();
            })
            .catch(function (err) {
                return hexo.exit(err);
            });
        });
    });

    // 压缩public目录下的js文件
    gulp.task("compressJs", function () {
        return gulp
        .src(["./public/**/*.js", "!./public/libs/**"]) //排除的js
        .pipe(gulpif(!isScriptAll, changed("./public")))
        .pipe(gulpif(isDebug, debug({ title: "Compress JS:" })))
        .pipe(plumber())
        .pipe(
            gulpBabel({
                presets: [es2015Preset] // es5检查机制
            })
        )
        .pipe(uglify()) //调用压缩组件方法uglify(),对合并的文件进行压缩
        .pipe(gulp.dest("./public")); //输出到目标目录
    });

    // 压缩public目录下的css文件
    gulp.task("compressCss", function () {
        var option = {
        rebase: false,
        //advanced: true, //类型:Boolean 默认:true [是否开启高级优化(合并选择器等)]
        compatibility: "ie7" //保留ie7及以下兼容写法 类型:String 默认:''or'*' [启用兼容模式; 'ie7':IE7兼容模式,'ie8':IE8兼容模式,'*':IE9+兼容模式]
        //keepBreaks: true, //类型:Boolean 默认:false [是否保留换行]
        //keepSpecialComments: '*' //保留所有特殊前缀 当你用autoprefixer生成的浏览器前缀,如果不加这个参数,有可能将会删除你的部分前缀
    };
    return gulp
        .src(["./public/**/*.css", "!./public/**/*.min.css"]) //排除的css
        .pipe(gulpif(!isScriptAll, changed("./public")))
        .pipe(gulpif(isDebug, debug({ title: "Compress CSS:" })))
        .pipe(plumber())
        .pipe(cleancss(option))
        .pipe(gulp.dest("./public"));
    });

    // 压缩public目录下的html文件
    gulp.task("compressHtml", function () {
        var cleanOptions = {
        protect: /<\!--%fooTemplate\b.*?%-->/g, //忽略处理
        unprotect: /<script [^>]*\btype="text\/x-handlebars-template"[\s\S]+?<\/script>/gi //特殊处理
    };
    var minOption = {
        collapseWhitespace: true, //压缩HTML
        collapseBooleanAttributes: true, //省略布尔属性的值 <input checked="true"/> ==> <input />
        removeEmptyAttributes: true, //删除所有空格作属性值 <input id="" /> ==> <input />
        removeScriptTypeAttributes: true, //删除<scripts>的type="text/javascript"
        removeStyleLinkTypeAttributes: true, //删除<style>和<link>的type="text/css"
        removeComments: true, //清除HTML注释
        minifyJS: true, //压缩页面JS
        minifyCSS: true, //压缩页面CSS
        minifyURLs: true //替换页面URL
    };
    return gulp
        .src("./public/**/*.html")
        .pipe(gulpif(isDebug, debug({ title: "Compress HTML:" })))
        .pipe(plumber())
        .pipe(htmlclean(cleanOptions))
        .pipe(htmlmin(minOption))
        .pipe(gulp.dest("./public"));
    });

    // 压缩 public/medias 目录内图片
    gulp.task("compressImage", function () {
        var option = {
        optimizationLevel: 5, //类型:Number 默认:3 取值范围:0-7(优化等级)
        progressive: true, //类型:Boolean 默认:false 无损压缩jpg图片
        interlaced: false, //类型:Boolean 默认:false 隔行扫描gif进行渲染
        multipass: false //类型:Boolean 默认:false 多次优化svg直到完全优化
    };
    return gulp
        .src("./public/medias/**/*.*")
        .pipe(gulpif(!isScriptAll, changed("./public/medias")))
        .pipe(gulpif(isDebug, debug({ title: "Compress Images:" })))
        .pipe(plumber())
        .pipe(imagemin(option))
        .pipe(gulp.dest("./public"));
    });
    // 执行顺序: 清除public目录 -> 产生原始博客内容 -> 执行压缩混淆 -> 部署到服务器
    gulp.task(
        "build",
        gulp.series(
            "clean",
            "generate",
            "compressHtml",
            "compressCss",
            "compressJs",
            "compressImage",
            gulp.parallel("deploy")
        )
    );

    // 默认任务
    gulp.task(
        "default",
        gulp.series(
            "clean",
            "generate",
            gulp.parallel("compressHtml", "compressCss", "compressJs","compressImage")
        )
    );
    //Gulp4最大的一个改变就是gulp.task函数现在只支持两个参数,分别是任务名和运行任务的函数

hexo-neat插件实现代码压缩

hexo-neat插件也是用来压缩代码的,底层也是通过gulp来实现的。但是这个插件是有Bug的。

压缩 md 文件会使 markdown 语法的代码块消失

会删除全角空格

在博客站点根目录执行安装代码:


npm install hexo-neat --save

紧接着在站点根目录下的配置文件(_config.yml)添加如下代码:


neat_enable: true
neat_html:
  enable: true
  exclude:
neat_css:
  enable: true
  exclude:
    - '*.min.css'
neat_js:
  enable: true
  mangle: true
  output:
  compress:
  exclude:
    - '*.min.js'

然后直接


hexo cl&&hexo g 

就可以了,会自动压缩文件 。

补充:

解决以上Bug,需要将以上默认配置修改为:


#hexo-neat 优化提速插件(去掉HTML、css、js的blank字符)
neat_enable: true
neat_html:
  enable: true
  exclude:
    - '**/*.md'
neat_css:
  enable: true
  exclude:
    - '**/*.min.css'
neat_js:
  enable: true
  mangle: true
  output:
  compress:
  exclude:
    - '**/*.min.js'
    - '**/**/instantpage.js'
    - '**/matery.js'

文章作者: Ming xin
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Ming xin !
评论
  目录