快速搭建博客:美化主題

其他搭建

請先觀看前幾篇博客
hexo4快速搭建博客(一)快速搭建一個博客
hexo4快速搭建博客(二)更換主題
其他博文:
hexo4快速搭建博客(四)寫作技巧包含圖牀和自動變圖牀的插件
hexo4搭建博客系列(五)優化博客(無坑) 部署到阿里雲
hexo4搭建博客系列(六)百度,必應,谷歌收錄(無坑)

然後下面這篇博文的美化幾乎很全,我自己也在用,如果有錯評論指出,寫得多自己腦子亂亂的。
我用的版本是 hexo4.0 + NexT7.6版本。我的個人博客

1. 添加博客圖標

如:1

在主題目錄下_config.yml文件查詢 favicon,只需要修改前兩個:small和medium,圖片的像素得爲16像素和32像素

favicon:
  small: /images/favicon-16x16-next.png
  medium: /images/favicon-32x32-next.png
  apple_touch_icon: /images/apple-touch-icon-next.png
  safari_pinned_tab: /images/logo.svg
  #android_manifest: /images/manifest.json
  #ms_browserconfig: /images/browserconfig.xml

你可以看到這兩個屬性的值,/images其實完整的路徑爲:themes/next/source/images 這條路徑來定位的。

也可以定義外部URI。

可以去圖標素材:iconfonteasyicon。中下載16x16和32x32大小的PNG格式圖片,然後放到themes/next/source/images下。

可以得出,要在主題某處添加什麼圖片都可以放在這個目錄下。

2. 鼠標點擊特效(二選一)

2.1 紅心特效

剛剛說了主題圖片可以放在themes\next\source\images,而themes\next\source有一個js文件,我們在themes\next\source\js\src(如果沒有就自己創建) 下新建文件clicklove.js,然後把下面的代碼copy到該文件中。

!function(e,t,a){function n(){c(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"),o(),r()}function r(){for(var e=0;e<d.length;e++)d[e].alpha<=0?(t.body.removeChild(d[e].el),d.splice(e,1)):(d[e].y--,d[e].scale+=.004,d[e].alpha-=.013,d[e].el.style.cssText="left:"+d[e].x+"px;top:"+d[e].y+"px;opacity:"+d[e].alpha+";transform:scale("+d[e].scale+","+d[e].scale+") rotate(45deg);background:"+d[e].color+";z-index:99999");requestAnimationFrame(r)}function o(){var t="function"==typeof e.onclick&&e.onclick;e.onclick=function(e){t&&t(),i(e)}}function i(e){var a=t.createElement("div");a.className="heart",d.push({el:a,x:e.clientX-5,y:e.clientY-5,scale:1,alpha:1,color:s()}),t.body.appendChild(a)}function c(e){var a=t.createElement("style");a.type="text/css";try{a.appendChild(t.createTextNode(e))}catch(t){a.styleSheet.cssText=e}t.getElementsByTagName("head")[0].appendChild(a)}function s(){return"rgb("+~~(255*Math.random())+","+~~(255*Math.random())+","+~~(255*Math.random())+")"}var d=[];e.requestAnimationFrame=function(){return e.requestAnimationFrame||e.webkitRequestAnimationFrame||e.mozRequestAnimationFrame||e.oRequestAnimationFrame||e.msRequestAnimationFrame||function(e){setTimeout(e,1e3/60)}}(),n()}(window,document);

然後在\themes\next\layout_layout.swig文件末尾添加:

<!-- 頁面點擊小紅心 -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>

2.2 爆炸煙花

在themes\next\source\js\src(如果沒有就自己創建) 下新建文件firework.js,然後把下面的代碼copy到該文件中。

"use strict";function updateCoords(e){pointerX=(e.clientX||e.touches[0].clientX)-canvasEl.getBoundingClientRect().left,pointerY=e.clientY||e.touches[0].clientY-canvasEl.getBoundingClientRect().top}function setParticuleDirection(e){var t=anime.random(0,360)*Math.PI/180,a=anime.random(50,180),n=[-1,1][anime.random(0,1)]*a;return{x:e.x+n*Math.cos(t),y:e.y+n*Math.sin(t)}}function createParticule(e,t){var a={};return a.x=e,a.y=t,a.color=colors[anime.random(0,colors.length-1)],a.radius=anime.random(16,32),a.endPos=setParticuleDirection(a),a.draw=function(){ctx.beginPath(),ctx.arc(a.x,a.y,a.radius,0,2*Math.PI,!0),ctx.fillStyle=a.color,ctx.fill()},a}function createCircle(e,t){var a={};return a.x=e,a.y=t,a.color="#F00",a.radius=0.1,a.alpha=0.5,a.lineWidth=6,a.draw=function(){ctx.globalAlpha=a.alpha,ctx.beginPath(),ctx.arc(a.x,a.y,a.radius,0,2*Math.PI,!0),ctx.lineWidth=a.lineWidth,ctx.strokeStyle=a.color,ctx.stroke(),ctx.globalAlpha=1},a}function renderParticule(e){for(var t=0;t<e.animatables.length;t++){e.animatables[t].target.draw()}}function animateParticules(e,t){for(var a=createCircle(e,t),n=[],i=0;i<numberOfParticules;i++){n.push(createParticule(e,t))}anime.timeline().add({targets:n,x:function(e){return e.endPos.x},y:function(e){return e.endPos.y},radius:0.1,duration:anime.random(1200,1800),easing:"easeOutExpo",update:renderParticule}).add({targets:a,radius:anime.random(80,160),lineWidth:0,alpha:{value:0,easing:"linear",duration:anime.random(600,800)},duration:anime.random(1200,1800),easing:"easeOutExpo",update:renderParticule,offset:0})}function debounce(e,t){var a;return function(){var n=this,i=arguments;clearTimeout(a),a=setTimeout(function(){e.apply(n,i)},t)}}var canvasEl=document.querySelector(".fireworks");if(canvasEl){var ctx=canvasEl.getContext("2d"),numberOfParticules=30,pointerX=0,pointerY=0,tap="mousedown",colors=["#FF1461","#18FF92","#5A87FF","#FBF38C"],setCanvasSize=debounce(function(){canvasEl.width=2*window.innerWidth,canvasEl.height=2*window.innerHeight,canvasEl.style.width=window.innerWidth+"px",canvasEl.style.height=window.innerHeight+"px",canvasEl.getContext("2d").scale(2,2)},500),render=anime({duration:1/0,update:function(){ctx.clearRect(0,0,canvasEl.width,canvasEl.height)}});document.addEventListener(tap,function(e){"sidebar"!==e.target.id&&"toggle-sidebar"!==e.target.id&&"A"!==e.target.nodeName&&"IMG"!==e.target.nodeName&&(render.play(),updateCoords(e),animateParticules(pointerX,pointerY))},!1),setCanvasSize(),window.addEventListener("resize",setCanvasSize,!1)}"use strict";function updateCoords(e){pointerX=(e.clientX||e.touches[0].clientX)-canvasEl.getBoundingClientRect().left,pointerY=e.clientY||e.touches[0].clientY-canvasEl.getBoundingClientRect().top}function setParticuleDirection(e){var t=anime.random(0,360)*Math.PI/180,a=anime.random(50,180),n=[-1,1][anime.random(0,1)]*a;return{x:e.x+n*Math.cos(t),y:e.y+n*Math.sin(t)}}function createParticule(e,t){var a={};return a.x=e,a.y=t,a.color=colors[anime.random(0,colors.length-1)],a.radius=anime.random(16,32),a.endPos=setParticuleDirection(a),a.draw=function(){ctx.beginPath(),ctx.arc(a.x,a.y,a.radius,0,2*Math.PI,!0),ctx.fillStyle=a.color,ctx.fill()},a}function createCircle(e,t){var a={};return a.x=e,a.y=t,a.color="#F00",a.radius=0.1,a.alpha=0.5,a.lineWidth=6,a.draw=function(){ctx.globalAlpha=a.alpha,ctx.beginPath(),ctx.arc(a.x,a.y,a.radius,0,2*Math.PI,!0),ctx.lineWidth=a.lineWidth,ctx.strokeStyle=a.color,ctx.stroke(),ctx.globalAlpha=1},a}function renderParticule(e){for(var t=0;t<e.animatables.length;t++){e.animatables[t].target.draw()}}function animateParticules(e,t){for(var a=createCircle(e,t),n=[],i=0;i<numberOfParticules;i++){n.push(createParticule(e,t))}anime.timeline().add({targets:n,x:function(e){return e.endPos.x},y:function(e){return e.endPos.y},radius:0.1,duration:anime.random(1200,1800),easing:"easeOutExpo",update:renderParticule}).add({targets:a,radius:anime.random(80,160),lineWidth:0,alpha:{value:0,easing:"linear",duration:anime.random(600,800)},duration:anime.random(1200,1800),easing:"easeOutExpo",update:renderParticule,offset:0})}function debounce(e,t){var a;return function(){var n=this,i=arguments;clearTimeout(a),a=setTimeout(function(){e.apply(n,i)},t)}}var canvasEl=document.querySelector(".fireworks");if(canvasEl){var ctx=canvasEl.getContext("2d"),numberOfParticules=30,pointerX=0,pointerY=0,tap="mousedown",colors=["#FF1461","#18FF92","#5A87FF","#FBF38C"],setCanvasSize=debounce(function(){canvasEl.width=2*window.innerWidth,canvasEl.height=2*window.innerHeight,canvasEl.style.width=window.innerWidth+"px",canvasEl.style.height=window.innerHeight+"px",canvasEl.getContext("2d").scale(2,2)},500),render=anime({duration:1/0,update:function(){ctx.clearRect(0,0,canvasEl.width,canvasEl.height)}});document.addEventListener(tap,function(e){"sidebar"!==e.target.id&&"toggle-sidebar"!==e.target.id&&"A"!==e.target.nodeName&&"IMG"!==e.target.nodeName&&(render.play(),updateCoords(e),animateParticules(pointerX,pointerY))},!1),setCanvasSize(),window.addEventListener("resize",setCanvasSize,!1)};

然後在\themes\next\layout_layout.swig文件末尾添加:

<!-- 爆炸煙花 -->
<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/src/firework.js"></script>

3. 設置頭像

在主題目錄(themes/next/)中的_config.yml,查找 avatar

# Sidebar Avatar
avatar:
  # Replace the default image and set the url here.
  # 把你要的頭像文件名字改爲avatar並放到相應路徑下,如果後綴不同,則在這裏改後綴,不要改圖片後綴
  url: /images/avatar.jpg 
  # If true, the avatar will be dispalyed in circle.
  rounded: true
  # If true, the avatar will be rotated with the cursor.
  rotated: true

4. 側邊欄社交小圖標設置

在主題目錄打開_config.yml,查詢 social

social:
  GitHub: https://github.com/magicflung || github
  #E-Mail: mailto:[email protected] || envelope
  #Weibo: https://weibo.com/yourname || weibo
  #Google: https://plus.google.com/yourname || google
  #Twitter: https://twitter.com/yourname || twitter
  #FB Page: https://www.facebook.com/yourname || facebook
  #StackOverflow: https://stackoverflow.com/yourname || stack-overflow
  #YouTube: https://youtube.com/yourname || youtube
  #Instagram: https://instagram.com/yourname || instagram
  #Skype: skype:yourname?call|chat || skype
  #RSS: /atom.xml || rss

然後啓動你想要的,並修改成自己的路徑。目前只有這些。

5. 文章末尾的標籤圖標修改

默認是 帶“#”,可以把它換成圖標。還是主題目錄打開_config.yml中查詢 tag_icon

# Use icon instead of the symbol # to indicate the tag at the bottom of the post
tag_icon: true

效果:

2

6. 訪問量統計

在主題目錄打開_config.yml,查詢 busuanzi

# Show Views / Visitors of the website / page with busuanzi.
# Get more information on http://ibruce.info/2015/04/04/busuanzi
busuanzi_count:
  enable: true # 是否開啓訪問量統計
  total_visitors: false # 本站訪客數
  total_visitors_icon: user
  total_views: true # 本站總訪問量
  total_views_icon: eye
  post_views: false # 文章訪問量,但我不喜歡用這個,因爲在我的網站首頁不會顯示每篇博文的訪問量,而是得點進博文,我用別的來統計,待會會說
  post_views_icon: eye

但是我當時配置時失效,我百度一下,找到解決方案,原來是不蒜子使用的七牛的域名被強制過期。。

在/themes/next/layout/_third-party/statistics中的busuanzi-counter.swig中,看最前面,如圖:

3

我是改了的,你把src中的改爲:

https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js

在主題目錄的/themes/next/layout/_partials/footer.swig,在最後添加上下面這條,可以自己修改顯示的位置。我忘記了是不是本來就有配,並且是否有下面代碼的第一條,如果有則在裏面添加。沒用就直接複製下面的。

{%- if theme.footer.powered.enable %}
  <span id="busuanzi_container_site_pv">
    本站總訪問量<span class="busuanzi-value" id="busuanzi_value_site_pv"></span>次
  </span>
{%- endif %}

注意:本地測試的訪問量剛開始會很大不正常,但是部署後是正常的,這點不用理。

7. 添加站內搜索

在站內按照搜索,站點目錄打開Git Bash,輸入:

sudo npm install hexo-generator-search --save

然後在站點目錄的_config.yml文件把下面代碼添加進去,不用修改。我測試過可以不配置下面的代碼,插件默認只索引文章(post),要想頁面(page)也能被檢索,則把path的值改爲all。

具體可參考官方:hexo-generator-search

# 搜索
search:
  path: search.xml
  field: post
  format: html
  limit: 10000

最後在主題目錄的_config.yml文件,查詢 local_search

# Local Search
# Dependencies: https://github.com/theme-next/hexo-generator-searchdb
local_search:
  enable: true # 開啓站內搜索
  # 如果自動,則通過更改輸入觸發搜索。
  # 如果是手動,則按回車鍵或搜索按鈕觸發搜索。
  trigger: auto
  # 顯示每篇文章的前n個結果,通過設置-1顯示所有結果
  top_n_per_article: 1
  # 將html字符串轉換爲可讀字符串。
  unescape: false
  # 加載頁面時預加載搜索數據。
  preload: false

8. 啓動閱讀更多按鈕

在主題目錄的_config.yml中,查詢:read_more_btn

# Read more button
# If true, the read more button will be displayed in excerpt section.
read_more_btn: true # 啓動

效果:

4

這裏需要額外說一下,必須在每篇博文的最前面有一堆默認鍵值對代碼那裏,添加上一個鍵: description,

然後冒號: :,然後再空格,添加上自己的小文段。

5

但是每次都得自己加太麻煩了,所以在站點目錄下的scaffolds文件中有個post文件,這個文件就是博文模板,點開就可以添加每篇博文的通用信息。我的如下:

---
title: {{ title }}
date: {{ date }}
tags:
categories:
copyright: true
top:
description:
---

9. 文章頂置(二選一,看看哪種簡單)

9.1 方法一

在站點目錄的 node_modules/hexo-generator-index/lib/generator.js 中,把改文件的代碼全改成

'use strict';
var pagination = require('hexo-pagination');
module.exports = function(locals){
  var config = this.config;
  var posts = locals.posts;
    posts.data = posts.data.sort(function(a, b) {
        if(a.top && b.top) { // 兩篇文章top都有定義
            if(a.top == b.top) return b.date - a.date; // 若top值一樣則按照文章日期降序排
            else return b.top - a.top; // 否則按照top值降序排
        }
        else if(a.top && !b.top) { // 以下是隻有一篇文章top有定義,那麼將有top的排在前面(這裏用異或操作居然不行233)
            return -1;
        }
        else if(!a.top && b.top) {
            return 1;
        }
        else return b.date - a.date; // 都沒定義按照文章日期降序排
    });
  var paginationDir = config.pagination_dir || 'page';
  return pagination('', posts, {
    perPage: config.index_generator.per_page,
    layout: ['index', 'archive'],
    format: paginationDir + '/%d/',
    data: {
      __index: true
    }
  });
};

然後可以在博文模板post中加個top鍵,值爲整數,並且值爲大越靠前。

9.2 方法二

在站點目錄下打開Git Bash,先把原先的頂置插件卸載了,然後再裝上hexo-generator-index-pin-top,輸入:

npm uninstall hexo-generator-index --save
npm install hexo-generator-index-pin-top --save

然後可以在博文模板post中加個top鍵,值爲整數,並且值爲大越靠前。

這種方法就不用去修改js文件。

最後,兩種都可以用的,就是在頂置博文時,沒用一個頂置圖標感覺有點怪怪的,所以可以加個圖標。在主題目錄中的themes\next\layout\_macro的post文件,打開查詢第一個:post-meta。

<div class="post-meta">

然後這個div的下一行添加上:

{% if post.top %}
	<i class="fa fa-thumb-tack"></i>
	<font color=7D26CD>置頂</font>
	<span class="post-meta-divider">|</span>
{% endif %}

效果:

6

10. 在文章底部增加版權信息

10.1 方式一

最簡單,在主題目錄的_config.yml查詢 creative_commons

# Creative Commons 4.0 International License.
# See: https://creativecommons.org/share-your-work/licensing-types-examples
# Available values of license: by | by-nc | by-nc-nd | by-nc-sa | by-nd | by-sa | zero
# You can set a language value if you prefer a translated version of CC license, e.g. deed.zh
# CC licenses are available in 39 languages, you can find the specific and correct abbreviation you need on https://creativecommons.org
creative_commons:
  license: by-nc-sa
  sidebar: false
  post: true # 開啓
  language:

但是這種如何改變樣式我沒研究,我喜歡下面的方式,畢竟還可以自己加上樣式、文字等。

10.2 方式二(比較麻煩,但是好看)

我用網上的直接複製的代碼,但是在這段代碼中的sweetalert外部鏈接不知道咋了,訪問超時,導致我的博文訪問一篇文章賊慢,我以爲是哪裏出錯。**這也是一個啓示:如果博文突然變得慢,打開web工具檢查一下那些加載過慢,考慮是否要刪去,或者是哪裏出錯。**如下圖:11s的加載。

7

所以出錯就是在這一句:

<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

我下載一個本地的js,然後自己改成本地連接就好了。

點擊下載,然後解壓,把sweetalert.min.js文件放到themes\next\source\js中,

在themes\next\layout_macro中新建一個 my-copyright.swig文件,並添加:

  {% if page.copyright %}
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>

  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
   <!-- JS庫 sweetalert 引用本地路徑 -->
  <script src="/js/sweetalert.min.js"></script>
  <p><span>文章作者:</span><a href="/" title="訪問 {{ theme.author }} 的個人博客">{{ theme.author }}</a></p>
  <p><span>發佈時間:</span>{{ page.date.format("YYYY年MM月DD日 - HH:MM") }}</p>
  <p><span>原始鏈接:</span><a href="{{ url_for(page.path) }}" title="{{ page.title }}">{{ page.permalink }}</a>
    <span class="copy-path"  title="點擊複製文章鏈接"><i class="fa fa-clipboard" data-clipboard-text="{{ page.permalink }}"  aria-label="複製成功!"></i></span>
  </p>
  <p><span>許可協議:</span> 轉載請保留原文鏈接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
      $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '複製成功',
          icon: "success", 
          showConfirmButton: true
          });
        });
    });  
</script>
{% endif %}

然後在themes\next\source\css_common\components\post中新建my-post-copyright.styl 文件,添加上我們的版權樣式。

.my_post_copyright {
  width: 85%;
  max-width: 45em;
  margin: 2.8em auto 0;
  padding: 0.5em 1.0em;
  border: 1px solid #d3d3d3;
  font-size: 0.93rem;
  line-height: 1.6em;
  word-break: break-all;
  background: rgba(255,255,255,0.4);
}
.my_post_copyright p{margin:0;}
.my_post_copyright span {
  display: inline-block;
  width: 5.2em;
  color: #b5b5b5;
  font-weight: bold;
}
.my_post_copyright .raw {
  margin-left: 1em;
  width: 5em;
}
.my_post_copyright a {
  color: #808080;
  border-bottom:0;
}
.my_post_copyright a:hover {
  color: #a3d2a3;
  text-decoration: underline;
}
.my_post_copyright:hover .fa-clipboard {
  color: #000;
}
.my_post_copyright .post-url:hover {
  font-weight: normal;
}
.my_post_copyright .copy-path {
  margin-left: 1em;
  width: 1em;
  +mobile(){display:none;}
}
.my_post_copyright .copy-path:hover {
  color: #808080;
  cursor: pointer;
}

然後在themes/next/layout/_macro/post.swig中,搜索 END POST BODY,然後再下一行添加:

<div>
	{% if not is_index %}
		{% include 'my-copyright.swig' %}
	{% endif %}
</div>

最後在themes/next/source/css/_common/components/post/post.styl文件中最後添加:

@import "my-post-copyright"

然後回到站點目錄下的scaffolds文件中有個post文件,添加copyright: true。也就是我上面那圖,這就會在每篇博文下添加版權信息,也方便別人複製你的url。

11. 添加打賞

在主題文件的_config.yml,查詢:reward

# Reward (Donate)
# Front-matter variable (unsupport animation).
reward_settings:
  # If true, reward will be displayed in every article by default.
  enable: true # 開啓打賞
  animation: true # 開啓動畫抖動,可以自己試試
  #comment: Donate comment here.

reward:
  wechatpay: /images/wechatpay.jpg # 放微信的收款碼
  alipay: /images/alipay.jpg # 放支付寶的收款碼
  #bitcoin: /images/bitcoin.png

12. 文章加密訪問

我不推薦用,畢竟只是前端校驗而已。雖然一般人破不出。

13. 啓動代碼複製按鈕

打開主題目錄的_config.yml,查詢 copy_button。

codeblock:
  # Code Highlight theme
  # Available values: normal | night | night eighties | night blue | night bright | solarized | solarized dark | galactic
  # See: https://github.com/chriskempson/tomorrow-theme
  highlight_theme: normal
  # Add copy button on codeblock
  copy_button:
    enable: true # 開啓代碼複製按鈕
    # Show text copy result.
    show_result: true
    # Available values: default | flat | mac
    style: mac # 代碼框樣式,我喜歡用mac的,上面有三個選擇都可以試試

14. 在Footer添加站點運行時間

在主題目錄的/themes/next/layout/_partials/footer.swig中找到下面這句。

{%- if theme.footer.theme.enable %}  

然後在這句的下面添加:

<div id="days"></div>
	</script>
	<script language="javascript">
	function show_date_time(){
	window.setTimeout("show_date_time()", 1000);
	BirthDay=new Date("11/29/2019 20:00:00");
	today=new Date();
	timeold=(today.getTime()-BirthDay.getTime());
	sectimeold=timeold/1000
	secondsold=Math.floor(sectimeold);
	msPerDay=24*60*60*1000
	e_daysold=timeold/msPerDay
	daysold=Math.floor(e_daysold);
	e_hrsold=(e_daysold-daysold)*24;
	hrsold=setzero(Math.floor(e_hrsold));
	e_minsold=(e_hrsold-hrsold)*60;
	minsold=setzero(Math.floor((e_hrsold-hrsold)*60));
	seconds=setzero(Math.floor((e_minsold-minsold)*60));
	document.getElementById('days').innerHTML="已運行"+daysold+"天"+hrsold+"時"+minsold+"分"+seconds+"秒";
	}
	function setzero(i){
	if (i<10)
	{i="0" + i};
	return i;
	}
	show_date_time();
	</script>

在這條語句裏面我把原先的代碼都註釋了,不想用。爲了怕說不清,貼圖:

8

15. 實現文章統計功能

安裝一個 hexo-symbols-count-time插件,可以統計字數和閱讀分鐘數,

npm install hexo-symbols-count-time --save

然後在站點目錄的config.yml最後添加:

symbols_count_time:
  symbols: true                # 文章字數統計
  time: true                   # 文章閱讀時長
  total_symbols: true          # 站點總字數統計
  total_time: true             # 站點總閱讀時長
  exclude_codeblock: false     # 排除代碼字數統計

不喜歡的可以使用false讓它不啓動。並且文章字數統計時,他是連空格,標點符號等都統計了,可能會導致文章的字數會不正確,偏大。

效果:

9

16. 修改博文目錄

在主題目錄的_config.yml 查詢 toc

# 側邊欄中的目錄
# Front-matter variable (unsupport wrap expand_all).
toc:
  enable: true # 是否啓動博文目標
  # 自動將列表號添加到目錄。
  number: false
  # 如果爲true,則如果標題寬度大於邊欄寬度,則所有單詞都將放在下一行。width.
  wrap: false
  # 如果爲true,則將顯示帖子中所有級別的TOC,而不是其中激活的部分。
  expand_all: false
  # 生成的子標題的最大深度。
  max_depth: 6

17. RSS訂閱(非必要)

原因:RSS訂閱可以對文章內容進行訂閱。如下:就不必每次去收藏夾找該博客網站

10

首先在站點目錄下打開Git Bash 安裝

npm install hexo-generator-feed --save

然後打開站點目錄的_config.yml在後面添加:

# RSS
plugins: hexo-generate-feed

然後在站點目錄的_config.yml 查找 RSS

然後把它的註釋去掉,即開啓,並且不用去創建該頁面,會自動生成

RSS: /atom.xml || rss

然後部署到網站就可以看到,但是我們點開時是一堆代碼,我們需要安裝一個RSS閱讀器的插件,在瀏覽器搜索

RSS,谷歌商城一般登不上,登得上一樣查RSS就行,那在火狐的附加工具搜,第一個就是下面這個:

11

安裝這個,使用方法:

12
13
14
RSS的URL就是我們點開後一堆代碼的上面的URL,比如我的是:

https://flunggg.cn/atom.xml

18. GitHub Fork Me

這個可以在我們的網站右上角出現一個到GitHub的跳轉按鈕,其實也跟側邊欄那個社交小圖標差不多功能

在主題目錄的_config.yml查詢 github_banner

# `Follow me on GitHub` banner in the top-right corner.
github_banner:
  enable: true # 開啓
  permalink: https://github.com/magicflung # 把它改爲你的github首頁
  title: Follow me on GitHub

19. bookmark

Bookmark是一個插件,允許用戶保存他們的閱讀進度。用戶只需單擊頁面左上角的書籤圖標即可保存滾動位置。當他們下次訪問您的博客時,他們可以自動恢復每個頁面的最後滾動位置。

在主題目錄的_config.yml查詢 bookmark

bookmark:
  enable: true # 開啓
  # Customize the color of the bookmark.
  color: "#836FFF" # 自定義顏色
  # If auto, save the reading progress when closing the page or clicking the bookmark-icon.
  # If manual, only save it by clicking the bookmark-icon.
  save: auto # 會自動保存閱讀進度

效果:

15

20. 添加lazyload(跟後面的圖片點擊全屏看不能共存)

對於圖片進行延遲加載,訪問到圖片位置時纔去請求圖片資源,這樣可以提高博客的訪問速度,節省流量。下面一整條都複製。

npm install --save lozad

然後在你的主題目錄的配置文件 _config.yml 中,查詢 lazyload

# Vanilla JavaScript plugin for lazyloading images.
# For more information: https://github.com/ApoorvSaxena/lozad.js
lazyload: true # 開啓

21. 顯示當前瀏覽進度(兩者可共存)

21.1 方式一

在主題目錄的_config.yml查詢scrollpercent,默認爲false,改爲true

back2top:
  enable: true
  # Back to top in sidebar.
  sidebar: false
  # Scroll percent label in b2t button.
  scrollpercent: true # 開啓

21.2 方式二

在主題目錄的_config.yml查詢reading_progress

# Reading progress bar
reading_progress:
  enable: true # 開啓
  # Available values: top | bottom
  position: top # top會出現在頁面最頂部,bottom會出現在那裏
  color: "#836FFF" # 可修改顏色
  height: 3px

22. Footer / 頁腳設置

在主題目錄的_config.yml 查詢 footer

footer:
  # Specify the date when the site was setup. If not defined, current year will be used.
  #since: 2019

  # Icon between year and copyright info.
  icon:
    # Icon name in Font Awesome. See: https://fontawesome.com/v4.7.0/icons/
    # `heart` is recommended with animation in red (#ff0000).
    name: heart # 可以修改圖片,可以去 https://fontawesome.com/v4.7.0/icons/ 找
    # If you want to animate the icon, set it to true.
    animated: true
    # Change the color of icon, using Hex Code.
    color: "#F5F5F5" # 圖標顏色

  # If not defined, `author` from Hexo `_config.yml` will be used.
  copyright:
  
  # Powered by Hexo 字樣,不喜歡可以設置爲 false
  powered:
    # Hexo link (Powered by Hexo).
    enable: true
    # Version info of Hexo after Hexo link (vX.X.X).
    version: true
    
  # 主題字樣,不喜歡可以 false
  theme:
    # Theme & scheme info link (Theme - NexT.scheme).
    enable: true
    # Version info of NexT after scheme info (vX.X.X).
    version: true

  # 備案信息,如果網站有備案號,可以在這裏填寫備案號
  # Beian ICP and gongan information for Chinese users. See: http://www.beian.miit.gov.cn, http://www.beian.gov.cn
  beian:
    enable: false
    icp:
    # The digit in the num of gongan beian.
    gongan_id:
    # The full num of gongan beian.
    gongan_num:
    # The icon for gongan beian. See: http://www.beian.gov.cn/portal/download
    gongan_icon_url:

然後還可以在 themes\next\layout_partials的footer.swig裏修改,這個我在前面的Footer添加運行時間有說,在這個文件可以修改他們的位置,也可以手動去掉或添加某些東西。如我的:

16

23. 添加Valine評論

評論系統有很多種,只能選一種。

我自己喜歡用不登錄評論,也就是偶爾有人要說一下,但是發現還得登錄。這個評論系統就是Valine,下面是教程:

23.1. 註冊LeanCloud

點擊LeanCloud,去註冊一個賬號,點右上角的控制檯就會跳到註冊。這裏有分爲國內和國際版,國內的在2019-10-1之後需要自定義已備案域名才能繼續提供服務了,覺得麻煩的同學可以移步去國際版LeanCloud國際版

23.2. 創建應用

註冊好之後,進行實名驗證、郵箱驗證等等。

點擊創建應用,輸入名稱,然後直接創建。

17

23.3. 設置Web安全域名,填入自己的域名

目的是:爲了數據安全。

打開應用,點擊 設置 -> 安全中心。看下面,把能訪問到你網站的URL全寫進去。

18

23.4. 獲取APP ID 和 APP Key

如下打開:

19

然後在主題目錄的_config.yml 文件查詢 valine,然後把上面的兩個複製進去

# Valine
# For more information: https://valine.js.org, https://github.com/xCss/Valine
valine:
  enable: true # 開啓
  appid:  # 添加你的appid
  appkey: # 添加你的appkey
  notify: false # Mail notifier
  verify: false # Verification code
  placeholder: Just go go # Comment box placeholder
  avatar: monsterid # Gravatar style
  guest_info: nick,mail,link # Custom comment header
  pageSize: 10 # Pagination size
  language: # Language, available values: en, zh-cn
  visitor: true # Article reading statistic
  comment_count: true # If false, comment count will only be displayed in post page, not in home page
  recordIP: false # Whether to record the commenter IP
  serverURLs: # When the custom domain name is enabled, fill it in here (it will be detected automatically by default, no need to fill in)
  #post_meta_order: 0
  avatar_cdn: https://www.gravatar.com/avatar/

效果圖是這樣的:

20

不過上面的 網址(http://) 我覺得沒什麼用,就把它去掉了,打開themes\next\layout_third-party\comments中的valine.swig文件,刪掉第三個,我的已經刪了:

21

也可以選擇Gitalk評論系統,這個我就不說了。要的自己百度。

24. Vline郵箱評論通知

每當有人在博文下面評論我們的博文,我們就可以使用這個插件通過郵箱知道。

下面這款插件是新款,有幾個優點:

  • 完善的郵件通知,自定義 SMTP 發件頻率和內容不再受限
  • 基於 Akismet 的垃圾評論自動標註和過濾
  • 評論管理,避免直接操作數據庫

效果:

22

1.我們還是要藉助Leancloud,打開剛剛我們創建的應用,如圖:修改右邊的邊框內容。這是配置回覆模板。
在這裏插入圖片描述

:請注意修改鏈接爲你的博客或者網站首頁

<p>Hi, {{username}}</p>
<p>
你在 {{appname}} 的評論收到了新的回覆,請點擊查看:
</p>
<p><a href="你的網址首頁鏈接" style="display: inline-block; padding: 10px 20px; border-radius: 4px; background-color: #3090e4; color: #fff; text-decoration: none;">馬上查看</a></p>

2.還是在Leancloud中,打開 雲引擎 -》設置,把下面代碼複製進去:

https://github.com/DesertsP/Valine-Admin.git

23

然後還是在這,點擊 部署,如圖:

24

上面的圖我用別人的,因爲我自己點開就是下面的圖:

25

然後等待部署完,比較久。

3.然後還是回到 雲引擎 -》 設置 中,如圖:找到 自定義環境變量

26

需要配置信息:

變量名 實例 說明
SITE_NAME flunggg 【必填】網站名稱
SITE_URL https://flunggg.cn/ 網站地址
SMTP_HOST smtp.qq.com QQ郵箱爲這個,其他的自己查
SMTP_PORT 465 Https的郵件端口
SMTP_USER [email protected] 這裏填寫QQ郵箱,然後有人評論就會發送到我們這個郵箱裏
SMTP_PASS 這裏添加郵箱申請的SMTP密碼
SENDER_NAME xxx博客–評論提醒 發送郵件的暱稱
SENDER_EMAIL 發送人郵箱,同上面的QQ郵箱一致就行
ADMIN_URL 管理評論後臺,這個待會說

4.如何申請SMTP,直接看圖,我用的是qq郵箱,你要用別的得去查。開啓後把STMP密碼複製到這。

27

5.設置二級域名後你可以訪問評論管理後臺。還是在這裏的下面找到 Web主機域名

28

現在好像已經是默認給你一個,不能改的,然後把這個域名複製到上面環境變量的ADMIN_URL。

我們還需要密碼,用戶名,需要在這裏設置,只需要填寫 email、password、username,這三個字段即可,使用 username 或 email 登陸即可。

29

30

然後重啓下實例

31

最後訪問域名,輸入我們剛剛的username或者email,登錄。就可以管理我們的評論區啦。

LeanCloud 休眠策略

免費版的 LeanCloud 容器,是有強制性休眠策略的,不能 24 小時運行:

  • 每天必須休眠 6 個小時
  • 30 分鐘內沒有外部請求,則休眠。
  • 休眠後如果有新的外部請求實例則馬上啓動(但激活時發送郵件會失敗)。

分析了一下上方的策略,如果不想付費的話,最佳使用方案就設置定時器,每天 7 - 23 點每 20 分鐘訪問一次,這樣可以保持每天的絕大多數時間郵件服務是正常的。

25. Valine 頭像設置

我們可以修改評論的頭像,路人的頭像有下面幾種,默認爲第一種

32

在主題目錄的_config.yml文件查找:valine 中,找到avatar,然後就可以修改上面的圖標

# Valine
# For more information: https://valine.js.org, https://github.com/xCss/Valine
valine:
  ...
  avatar: monsterid # Gravatar style
  ... 

如果你修改了頭像後發現沒有更新,請不要慌張,因爲gravatar.cat.net 有七天的緩存期,安靜的等待吧

然後還可以設置自己的自定義頭像,登錄 gravatar,註冊賬號並設置頭像,然後在valine評論時,輸入我們剛剛註冊的郵箱,會顯示出我們自定義的頭像。我的設置如下:

33

26. 添加文章閱讀次數

這個還是得藉助Leancloud

在主題目錄的_config.yml 查詢 leancloud_visitors

![23](D:\myblog\blog\source\_posts\hexo4-NexT7搭建博客(四)\23.png)# Show number of visitors of each article.
# You can visit https://leancloud.cn to get AppID and AppKey.
# AppID and AppKey are recommended to be the same as valine's for counter compatibility.
# Do not enable both `valine.visitor` and `leancloud_visitors`.
leancloud_visitors:
  enable: true # 開啓
  app_id: # 填入你的Leancloud的appId
  app_key: # 填入你的Leancloud的appKey
  # Dependencies: https://github.com/theme-next/hexo-leancloud-counter-security
  # If you don't care about security in leancloud counter and just want to use it directly
  # (without hexo-leancloud-counter-security plugin), set `security` to `false`.
  security: false # 默認
  betterPerformance: false # 默認

點擊剛剛創建的應用(評論那個),點擊設置->應用Keys中的Id和Key。複製粘貼到上面那個地方。然後在該應用,有一個叫 存儲,點開,然後看到創建Class,創建一個Counter就行。

34

35

27. Url 持久化

我們可以發現 hexo 默認生成的文章地址路徑是 【網站名稱/年/月/日/文章名稱】

這種鏈接對搜索爬蟲是很不友好的,它的 url 結構超過了三層,太深了。

下面我推薦安裝 hexo-abbrlink 插件:

npm install hexo-abbrlink --save

然後在站點目錄下,查詢 permalink

# URL
## If your site is put in a subdirectory, set url as 'http://yoursite.com/child' and root as '/child/'
url: https://flunggg.cn/  # 這裏我填寫我自己的域名,沒有域名的先別動
root: /
permalink: archives/:abbrlink.html # 該這個
abbrlink:
  alg: crc32  # 算法:crc16(default) and crc32
  rep: hex    # 進制:dec(default) and hex

效果:

36

28. nofollow 標籤的使用

減少出站鏈接能夠有效防止權重分散。簡單的說就是,如果A網頁上有一個鏈接指向B網頁,但A網頁給這個鏈接加上了 rel=“nofollow” 標註,則搜索引擎不把A網頁計算入B網頁的反向鏈接搜索引擎看到這個標籤就可能減少或完全取消鏈接的投票權重。(百度百科)

安裝插件:

npm install hexo-autonofollow --save

然後在站點目錄下的_config.yml添加

# 外部鏈接優化
nofollow:
    enable: true
    exclude:     # 例外的鏈接,可將友情鏈接放置此處
    - 'yousite'

這樣,例外的鏈接將不會被加上 nofollow 屬性。

29. 取消“文章目錄”的自動編號

在主題目錄下的_config.yml,搜索 toc

toc:
  enable: true
  # Automatically add list number to toc.
  number: false # 取消自動編號
  # If true, all words will placed on next lines if header width longer then sidebar width.
  wrap: true
  # If true, all level of TOC in a post will be displayed, rather than the activated part of it.
  expand_all: false
  # Maximum heading depth of generated toc.
  max_depth: 6

30. 背景(不要共存)

30.1 雨代碼(就是我當前用的這樣)

重頭戲來了,我第一次發現這個也是驚喜一番。

在主題目錄下的themes\next\source\js\src中新建一個名爲DigitalRain.js文件。然後添加如下代碼:

window.onload = function(){
    //獲取畫布對象
    var canvas = document.getElementById("canvas");
    //獲取畫布的上下文
    var context =canvas.getContext("2d");
    var s = window.screen;
    var W = canvas.width = s.width;
    var H = canvas.height;
    //獲取瀏覽器屏幕的寬度和高度
    //var W = window.innerWidth;
    //var H = window.innerHeight;
    //設置canvas的寬度和高度
    canvas.width = W;
    canvas.height = H;
    //每個文字的字體大小
    var fontSize = 12;
    //計算列
    var colunms = Math.floor(W /fontSize);	
    //記錄每列文字的y軸座標
    var drops = [];
    //給每一個文字初始化一個起始點的位置
    for(var i=0;i<colunms;i++){
        drops.push(0);
    }
    //運動的文字
    var str ="WELCOME TO WWW.ITRHX.COM";
    //4:fillText(str,x,y);原理就是去更改y的座標位置
    //繪畫的函數
    function draw(){
        context.fillStyle = "rgba(238,238,238,.08)";//遮蓋層
        context.fillRect(0,0,W,H);
        //給字體設置樣式
        context.font = "600 "+fontSize+"px  Georgia";
        //給字體添加顏色
        context.fillStyle = ["#33B5E5", "#0099CC", "#AA66CC", "#9933CC", "#99CC00", "#669900", "#FFBB33", "#FF8800", "#FF4444", "#CC0000"][parseInt(Math.random() * 10)];//randColor();可以rgb,hsl, 標準色,十六進制顏色
        //寫入畫布中
        for(var i=0;i<colunms;i++){
            var index = Math.floor(Math.random() * str.length);
            var x = i*fontSize;
            var y = drops[i] *fontSize;
            context.fillText(str[index],x,y);
            //如果要改變時間,肯定就是改變每次他的起點
            if(y >= canvas.height && Math.random() > 0.99){
                drops[i] = 0;
            }
            drops[i]++;
        }
    };
    function randColor(){//隨機顏色
        var r = Math.floor(Math.random() * 256);
        var g = Math.floor(Math.random() * 256);
        var b = Math.floor(Math.random() * 256);
        return "rgb("+r+","+g+","+b+")";
    }
    draw();
    setInterval(draw,35);
};

然後在主題目錄themes\next\layout下的_layout.swig文件中,在</html>上添加如下代碼:

<!-- 數字雨 -->
<canvas id="canvas" width="1440" height="900" ></canvas>
<script type="text/javascript" src="/js/DigitalRain.js"></script>

並且,在主題目錄的配置文件_config.yml中查找 custom_file_path

# Define custom file paths.
# Create your custom files in site directory `source/_data` and uncomment needed files below.
custom_file_path:
  #head: source/_data/head.swig
  #header: source/_data/header.swig
  #sidebar: source/_data/sidebar.swig
  #postMeta: source/_data/post-meta.swig
  #postBodyEnd: source/_data/post-body-end.swig
  #footer: source/_data/footer.swig
  #bodyEnd: source/_data/body-end.swig
  #variable: source/_data/variables.styl
  mixin: source/_data/mixins.styl
  style: source/_data/styles.styl

這些文件可以自定義css,只需要開啓(把#去掉)就行。然後根據路徑創建該文件,或者可以自定義文件路徑然後去創建。我在source/_data/styles.styl中添加如下代碼:

canvas {
  position: fixed;
  right: 0px;
  bottom: 0px;
  min-width: 100%;
  min-height: 100%;
  height: auto;
  width: auto;
  z-index: -1;
}

30.2 自定義背景圖

像上面那樣,去開啓一個css文件路徑,然後添加代碼:

// 添加背景圖片
body {
  background: url(/images/background.jpg); // 你給的背景圖
  -moz-background-size:100% 100%;
  -webkit-background-size:100% 100%;
  top: 0;
  left: 0;
  z-index: -2;
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-position: 50% 50%;
  background-size: cover;
}

30.3 其他背景

其他背景都可以在主題目錄配置文件_config.yml ,查詢 canvas_nest和canvas_ribbon,我就不說了,具體參考官方:Canvas-nestCanvas-ribbon。得先安裝才能開啓。

31. 瀏覽器網頁標題惡搞(轉,有貼轉載地址)

效果:

37

38

當用戶訪問你的博客時點擊到了其他網頁,我們可以惡搞一下網頁標題,呼喚用戶回來,首先在目錄 \Hexo\themes\hexo-theme-spfk\source\js 下新建一個 FunnyTitle.js 文件,在裏面填寫如下代碼:

<!--瀏覽器搞笑標題-->
 var OriginTitle = document.title;
 var titleTime;
 document.addEventListener('visibilitychange', function () {
     if (document.hidden) {
         $('[rel="icon"]').attr('href', "/img/trhx2.png");
         document.title = 'ヽ(●-`Д´-)ノ你醜你就走!';
         clearTimeout(titleTime);
     }
     else {
         $('[rel="icon"]').attr('href', "/img/trhx2.png");
         document.title = 'ヾ(Ő∀Ő3)ノ你帥就回來!' + OriginTitle;
         titleTime = setTimeout(function () {
             document.title = OriginTitle;
         }, 2000);
     }
 });

然後在主題目錄themes\next\layout下的_layout.swig文件中,在</html>上添加如下代碼:

<!--瀏覽器搞笑標題-->
<script type="text/javascript" src="/js/src/FunnyTitle.js"></script>

32. 一些樣式

還是剛剛的主題目錄的配置文件_config.yml中查找 custom_file_path

# Define custom file paths.
# Create your custom files in site directory `source/_data` and uncomment needed files below.
custom_file_path:
  #head: source/_data/head.swig
  #header: source/_data/header.swig
  #sidebar: source/_data/sidebar.swig
  #postMeta: source/_data/post-meta.swig
  #postBodyEnd: source/_data/post-body-end.swig
  #footer: source/_data/footer.swig
  #bodyEnd: source/_data/body-end.swig
  #variable: source/_data/variables.styl
  mixin: source/_data/mixins.styl
  style: source/_data/styles.styl

source/_data/styles.styl中添加如下代碼:下面的屬性都可以在自己的網站按F12來查看要修改哪裏,這應該不用我廢話了。我的CSS都是複製別人的,自己不會CSS。

// 文章之間的分割線
.posts-expand .post-eof {
  margin: 4em auto 4em;
  background: white;
}
// 標題欄
.site-meta {
// 這些自定義添加
}
// 底部文字
.footer-inner {
  font-size: 17px;
  color:  #262626;
  font-family: 'EB Garamond',"Noto Serif SC",sans-serif;
  font-weight: bold;
}
.fa-heart {
  color: red;
}
.post-meta-item-icon {
  color: red;
}
.footer {
// 這些自定義添加
}
// 修改主體透明度
.main-inner {
  background: #000;
  opacity: 0.90;
  padding-right: 3px;
  padding-left: 3px;
}
//主頁文章添加陰影效果
.post {
  margin-top: 30px;
  margin-bottom: 30px;
  padding: 25px;
  -webkit-box-shadow: 0 0 5px rgba(202, 203, 203, .5);
  -moz-box-shadow: 0 0 5px rgba(202, 203, 204, .5);
}
// 移動端
@media (max-width: 767px) {
  .post-block {
    padding-right:10px;
  }
  .posts-expand .post-eof {
    margin: 4em auto 4em;
    background: white;
  }
}

33. 一些修改

比如,默認這裏是很長的,我現在是改了,太長會導致手機端顯示不好,所以可以改

  • 電腦端:

39

  • 手機端:

40

在主題目錄themes\next\layout\_macro的post.swig中修改。主要是加個換行。

41

搜索:if theme.leancloud_visitors.enable 。然後在這上面添加如下代碼:

{#添加換行#}
<br>

有幫助的請給我點個贊

參考:

小丁的個人博客

評論郵箱參考

Valine官方

雨代碼,標題惡搞

hexo4.0 - Next7.2.4 主題優化配置

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章