【Blog】Hexo_Next_博客搭建记 (by onlychristmas)

与我而言,建立个人博客存在的意义有两个。
一方面,当作自己的备忘录,记录零散的知识点,避免重复的搜索工作;
另一方面,可以更好的分享一些自己的心得,方便与大家交流。
选择GitHub_Hexo_Next的组合的主要原因就是方便、便宜、简单,为从来没有接触过前端的自己降低难度。
为了能让博客漂亮一点,这几天来的折腾过程记录整理在此,以备遗忘。


因为优化后的个人博客中有写自定义语法,所以写作辅助小节的样式展示不完全正确,可以移步
好望角

如果转载,请转载个人博客地址(好望角)中原文。



博客搭建


本地构建博客

我的环境是win10系统,经过一下步骤可以构建好一个运行在本地的静态博客(电脑不能占用localhost:4000端口)
- 安装Node.js, 这是建立Hexo的基础。在powershell中验证是否安装成功用后面两条命令 node -vnpm -v
- 建立一个存放博客文件的新文件夹。按住shift单击右键点击‘在此处打开Powershell’
- 安装Hexo,并初始化博客(需要几分钟)

npm install -g hexo-cli
hexo init blog
  • 开启本地服务器
hexo new 我就是试试博客搭建好没
hexo g
hexo s

关联GitHub

要想将本地博客部署到gitpages上,按照下面步骤操作即可。
- 安装分布式版本控制系统Git, 这是下载地址这是git教程
- 没有github账户的先注册一个
- 要将本地的git和github账户绑定,打开git bash ,配置如下信息。

git config --global user.name "你的GitHub用户名"
git config --global user.email "你的GitHub注册邮箱"
  • 生成ssh密钥文件的命令:ssh-keygen -t rsa -C "你的GitHub注册邮箱",中间不需要设置什么,直接三个回车。
  • 在这里 点击 New SSH key 新建一个链接,并将C://users/用户名/.ssh/id_rsa.pub文件中的密钥复制进去(标题随便填)。
  • bash中输入ssh [email protected]验证是否配置成功。如果出现Hi 你的用户名!You've successfully authenticated ,,,bala,,,Connection to github.com closed证明连接成功,以后推送的时候只需第一次输入密码,以后直接推送即可。
  • 在github中新建一个仓库,名字是默认写法用户名.github.io 例如:OnlyChristmas.github.io
  • 站点配置文件 配置如下信息:
deploy:
  type: git
  repo: https://github.com/OnlyChristmas/OnlyChristmas.github.io.git # 你的代码仓库地址,记得后面加上`.git`
  branch: master
  • 然后保存你的配置文件
npm install hexo-deployer-git --save
  • 让你的博客上线!
hexo clean
hexo g
hexo d

绑定域名

穷学生现在先不考虑

初探Hexo

npm install hexo -g #安装Hexo
npm update hexo -g #升级
hexo init #初始化博客

# 主要命令的含义以及简写
hexo n "我的博客" == hexo new "我的博客" #新建文章
hexo g == hexo generate #生成
hexo s == hexo server #启动服务预览
hexo d == hexo deploy #部署

# 可能用到的设置命令
hexo server #Hexo会监视文件变动并自动更新,无须重启服务器
hexo server -s #静态模式
hexo server -p 5000 #更改端口
hexo server -i 192.168.1.1 #自定义 IP
hexo clean #清除缓存,若是网页正常情况下可以忽略这条命令
  • 图片是博客必不可少的一部分,但它们会造成加载缓慢。所以对于我们严肃的技术博客来说,就要少贴图,多敲代码,哈哈~。
    但是偶尔也是要贴几张图,才能说得更明白,这个时候推荐使用七牛云的外链,来提高速度。

  • 虽然我们是个严肃的技术博客,要有学术风格(就是丑!),但也不能太丑吧!?所以我这里换用Next主题,配置方式如下。当然也有更多的漂亮主题可供挑选,只是在配置的时候如是出现问题,更难解决,新手慎用。
    在blog文件夹下的shell中输入,下载主题文件。

    git clone https://github.com/iissnan/hexo-theme-next themes/next

    然后在 站点配置文件 配置如下信息:

# Extensions
## Plugins: https://hexo.io/plugins/
## Themes: https://hexo.io/themes/
# theme: landscape
theme: next

Next内置优化


优化虽好,可不要贪多哦。全打开的话网页加载会很慢。。。

选择Next主题中的风格样式

  • 主题配置文件 中搜索到如下这部分,并在四种风格中选择一个即可。
# Schemes
# scheme: Muse
# scheme: Mist   
# scheme: Pisces  
scheme: Gemini   

algolia搜索

首先在 algolia 注册账号。此处优化需注意,官方文档不够完善。
- 创建APIKey HEXO_ALGOLIA_INDEXING_KEY
- 进入Algolia的API Keys页面ALL API KEYS选项卡
- 创建APIKey
- Description:HEXO_ALGOLIA_INDEXING_KEY
- Indices:<此处选择之前创建的Index>
- ACL:Add records,Delete records,List indices,Delete index

也就是说,我们有两个APIKey,其中一个是Search-only API Key(我们后面需要进行用它配置),另一个是HEXO_ALGOLIA_INDEXING_KEY(新建好即可)。
具体的配置步骤如下:
- 在 站点配置文件 中需要添加
“`
algolia:
applicationID: # Application ID
apiKey: # Search-only API Key
indexName: # 此处选择之前创建的Index
chunkSize: 5000

```
  • 主题配置文件 中搜索到如下这部分,只需将enable改为true,最后两个搜索提示信息有需要的话也可以修改。

    algolia_search:
    enable: true
    hits:
    per_page: 10
    labels:
    input_placeholder: Search for Posts
    hits_empty: "不好意思,木有'${query}'的搜索结果?"
    hits_stats: "${hits} results found in ${time} ms"
  • 接下来,我采取的配置方法和官方文档有点出入,但是亲测有效(我是win10系统)。
    1. 在博客文件夹根目录右键打开git bash here
    2. export HEXO_ALGOLIA_INDEXING_KEY= 'Search-only API Key'
    3. hexo algolia

  • bash中出现类似提示说明配置成功

    INFO  [Algolia] Identified 6 pages and posts to index.
    INFO  [Algolia] Indexing chunk 1 of 1 (50 items each)
    INFO  [Algolia] Indexing done.

选择动画背景

  • 主题配置文件 中搜索并配置如下信息,最好四选一。
# Canvas-nest
canvas_nest: true   # 背景有降落伞

# three_waves
three_waves: false    # 背景有像海浪一样的小球球

# canvas_lines
canvas_lines: false    # 背景有立体蜘蛛网

# canvas_sphere
canvas_sphere: false    # 屏幕中央有一个爆炸状的球球

代码块语法高亮设置

  • 站点配置文件 设置
highlight:
  enable: true
  line_number: true
  auto_detect: true
  tab_replace: true

注意,网上的自定义样式优化代码中,有对代码块的优化,那部分代码需要注释掉。

添加RSS

  • 打开博客根目录,shell安装插件,用如下代码:
npm install --save hexo-generator-feed
  • 站点配置文件 配置如下信息:
# Extensions
## Plugins: http://hexo.io/plugins/
#RSS订阅
plugin:
- hexo-generator-feed
#Feed Atom
feed:
  type: atom
  path: atom.xml
  limit: 20
  hub:
  content:
  content_limit: 140
  content_limit_delim: ' '
  • 主题配置文件 中搜索并配置如下信息。
# Set rss to false to disable feed link.
# Leave rss as empty to use site's feed link.
# Set rss to specific value if you have burned your feed already.
rss: "/atom.xml"
  • 最后重新生成,只要在./public中看到atom.xml说明生成成功。

修改文章底部的tag图标

  • 修改模板/themes/next/layout/_macro/post.swig,搜索 rel="tag">#,将 # 换成<i class="fa fa-tag"></i>,当然也可以切换成任何你喜欢的小图标。

busuanzi统计访客人数

主题配置文件 中搜索并配置如下信息,也可以根据自己的喜欢修改其他配置。

# Show PV/UV of the website/page with busuanzi.
# Get more information on http://ibruce.info/2015/04/04/busuanzi/
busuanzi_count:
  # count values only if the other configs are false
  enable: true
  # custom uv span for the whole site
  site_uv: true
  site_uv_header: <i class="fa fa-user"></i> 你是第
  site_uv_footer: 个小伙伴
  # custom pv span for the whole site
  site_pv: true
  site_pv_header: <i class="fa fa-eye"></i> 总访问
  site_pv_footer: 人次
  # custom pv span for one page only
  page_pv: false
  page_pv_header: <i class="fa fa-file-o"></i>
  page_pv_footer:

文章的阅读数自定义

  • 首先要注册leancloud,获取AppID and AppKey。
  • 主题配置文件 中搜索并配置如下信息:
# Show number of visitors to each article.
# You can visit https://leancloud.cn get AppID and AppKey.
leancloud_visitors:
  enable: true
  app_id:  #<app_id>
  app_key:  #<app_key>
  • 打开/themes/next/layout/_macro/post.swig,我的代码修改成如下样子,也可以自由发挥。
          {# LeanCould PageView #}
          {% if theme.leancloud_visitors.enable %}
             <span id="{{ url_for(post.path) }}" class="leancloud_visitors" data-flag-title="{{ post.title }}">
               <span class="post-meta-divider">|</span>

               <!-- 注释掉了图片 -->
          <!-- <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>   -->

               {% if theme.post_meta.item_text %}
                 <span class="post-meta-item-text">{{__('post.visitors')}}&#58;</span>
               {% endif %}
                 <span class="leancloud-visitors-count"></span>
                 <span></span>
             </span>
          {% endif %}
  • 最后,在/themes/next/languages/zh-Hans.yml,可以任意修改文字信息,我的代码如下所示:
post:
  created: 创建于
  modified: 更新于
  sticky: 置顶
  posted: '发表于:'
  in: '类别:'
  read_more: 阅读全文
  untitled: 未命名
  toc_empty: 此文章未包含目录
  visitors: 热度

字数统计功能配置

  • 切换到根目录下,然后运行如下代码
$ npm install hexo-wordcount --save
  • 然后在 主题配置文件 中自定义如下配置:
# Post wordcount display settings
# Dependencies: https://github.com/willin/hexo-wordcount
post_wordcount:
  item_text: true
  wordcount: true
  min2read: false
  totalcount: true
  separated_meta: true

这里我遇到一个大坑,在正文中写``标签一定要用代码块包括,否则可能会造成wordcount无法正常统计字数!一直显示为0

解决readme问题

在github手动添加readme文件总是会被擦掉,会很麻烦,现在有两种解决方法。
- 第一种,在/blog/source中添加一个README.MDOWN文件,每次推送到github都可以正常解析。
- 第二种,在 站点配置文件 配置如下信息:

skip_render: README.md

自定义网站图标

  • 主题配置文件 中搜索到如下这部分,
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
  small: # 你的图像
  medium: # 你的图像
  apple_touch_icon: # 你的图像
  safari_pinned_tab: # 你的图像
  #android_manifest: /images/manifest.json
  #ms_browserconfig: /images/browserconfig.xml

网站顶部加载条

  • 已经被Next主题做成了默认的设置,在 主题配置文件 中配置:
# Progress bar in the top during page loading.
pace: true
# Themes list:
#pace-theme-big-counter
#pace-theme-bounce
#pace-theme-barber-shop
#pace-theme-center-atom
#pace-theme-center-circle
#pace-theme-center-radar
#pace-theme-center-simple
#pace-theme-corner-indicator
#pace-theme-fill-left
#pace-theme-flash
#pace-theme-loading-bar
#pace-theme-mac-osx
#pace-theme-minimal
# For example
# pace_theme: pace-theme-center-simple
pace_theme: pace-theme-minimal

版权信息

  • 已经被Next主题做成了默认的设置,在 主题配置文件 中配置:
footer:
  # Specify the date when the site was setup.
  # If not defined, current year will be used.
  since: 2018

  # Icon between year and copyright info.
  icon: heart

  # If not defined, will be used `author` from Hexo main config.
  copyright:
  # -------------------------------------------------------------
  # Hexo link (Powered by Hexo).
  powered: false

  theme:
    # Theme & scheme info link (Theme - NexT.scheme).
    enable: false
    # Version info of NexT after scheme info (vX.X.X).
    version: true
  • 可以在每天博文生成的时候,将它作为一个文章模板。这样可以灵活地对于每篇文章设定是否需要版权信息。
  • 我在/blog/scaffolds/中新建了一个next博文模板,代码如下:
---
title: {{ title }}
date: {{ date }}
comments: true
categories: NLP
tags: [tag1, tag2]
post_copyright: true
---
 This is a summary
<!-- more -->
  • 站点配置文件 配置如下信息,每次新生成的文章都会使用此模板。
#### Writing
new_post_name: :title.md # File name of new posts
default_layout: next

SEO配置

  • 想要让我们的站点被搜索引擎收录,要提交给他们站点文件。
  • 首先安装两个插件,并生成两个站点文件,sitemap.xml与baidusitemap.xml文件
npm install hexo-generator-sitemap --save-dev
hexo d -g
npm install hexo-generator-baidu-sitemap --save-dev
hexo d -g
  • 站点配置文件 配置如下信息:
# SEO 优化
sitemap:
  path: sitemap.xml
baidusitemap:
  path: baidusitemap.xml
  • 新建robots.txt文件,添加以下文件内容,把robots.txt放在hexo站点的source文件下
User-agent: * Allow: /
Allow: /archives/
Disallow: /vendors/
Disallow: /js/
Disallow: /css/
Disallow: /fonts/
Disallow: /vendors/
Disallow: /fancybox/
Sitemap: http://thief.one/sitemap.xml
Sitemap: http://thief.one/baidusitemap.xml
  • 主题配置文件 中配置如下。
# Enable baidu push so that the blog will push the url to baidu automatically which is very helpful for SEO
baidu_push: true

博客的统计信息

  • 主题配置文件 中有若干种分析工具可以配置,我这里只配置了谷歌分析
# Google Analytics
google_analytics: # 你的账号

gitment评论系统

先注册gitment,这是作者博客,按照官方文档搭建即可

# Gitment
# Introduction: https://imsun.net/posts/gitment-introduction/
# You can get your Github ID from https://api.github.com/users/<Github username>
gitment:
  enable: true
  mint: true # RECOMMEND, A mint on Gitment, to support count, language and proxy_gateway
  count: false # Show comments count in post meta area
  lazy: false # Comments lazy loading with a button
  cleanly: false # Hide 'Powered by ...' on footer, and more
  language: # Force language, or auto switch by theme
  github_user: OnlyChristmas # MUST HAVE, Your Github ID
  github_repo: OnlyChristmas.github.io # MUST HAVE, The repo you use to store Gitment comments
  client_id: 8fc5c43242323koljoa # MUST HAVE, Github client id for the Gitment
  client_secret: 4ff9a214325312515151b04c400d46 # EITHER this or proxy_gateway, Github access secret token for the Gitment
  proxy_gateway: # Address of api proxy, See: https://github.com/aimingoo/intersect
  redirect_protocol: # Protocol of redirect_uri with force_redirect_protocol when mint enabled

自定义优化


优化虽好,可不要贪多哦。全打开的话网页加载会很慢。。。

百度分享

next内置的代码在服务器升级https之后,百度分享的js请求不了。但是在 github上的轮子 可以修改后再其启用这一功能。

  • 下载后得到static文件夹,放入到/themes/next/source/目录下。
  • themes/next/layout/_partials/share/baidushare.swig中末尾处的代码进行替换。前面是原有代码,下面是替换的代码。
<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];
</script>
<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];
</script>
  • 最后一定记得先hexo ghexo s,否则可能会出现问题。

自定义网页title

next\source\js\src下新建脚本custom_title.js,将下面代码复制进去。 js脚本来源


<!--崩溃欺骗-->
 var OriginTitle = document.title;
 var titleTime;
 document.addEventListener('visibilitychange', function () {
     if (document.hidden) {
         $('[rel="icon"]').attr('href', "/img/TEP.ico");
         document.title = '╭(°A°`)╮ 爱我别走 ~';
         clearTimeout(titleTime);
     }
     else {
         $('[rel="icon"]').attr('href', "/favicon.ico");
         document.title = '(ฅ>ω<*ฅ) 这才对嘛~' + OriginTitle;
         titleTime = setTimeout(function () {
             document.title = OriginTitle;
         }, 2000);
     }
 });

next\layout\_layout.swig<body> </body>标签体内添加

  <!--崩溃欺骗-->
  <script type="text/javascript" src="/js/src/custom_title.js"></script>

鼠标点击事件及样式

设置鼠标点击桃心样式
  • /themes/next/source/js/src/中新建love.js,其中写入的代码如下。

    !function(e,t,a){function r(){for(var e=0;e<n.length;e++)n[e].alpha<=0?(t.body.removeChild(n[e].el),n.splice(e,1)):(n[e].y--,n[e].scale+=.004,n[e].alpha-=.013,n[e].el.style.cssText="left:"+n[e].x+"px;top:"+n[e].y+"px;opacity:"+n[e].alpha+";transform:scale("+n[e].scale+","+n[e].scale+") rotate(45deg);background:"+n[e].color+";z-index:99999");requestAnimationFrame(r)}var n=[];e.requestAnimationFrame=e.requestAnimationFrame||e.webkitRequestAnimationFrame||e.mozRequestAnimationFrame||e.oRequestAnimationFrame||e.msRequestAnimationFrame||function(e){setTimeout(e,1e3/60)},function(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)}(".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;}"),function(){var a="function"==typeof e.onclick&&e.onclick;e.onclick=function(e){a&&a(),function(e){var a=t.createElement("div");a.className="heart",n.push({el:a,x:e.clientX-5,y:e.clientY-5,scale:1,alpha:1,color:"rgb("+~~(255*Math.random())+","+~~(255*Math.random())+","+~~(255*Math.random())+")"}),t.body.appendChild(a)}(e)}}(),r()}(window,document);
  • /themes/next/layout/_layout.swig中的<body></body>标签体内添加下面代码。

      <!-- 页面点击小红心 -->
      <script type="text/javascript" src="/js/src/love.js"></script>
设置鼠标点击烟花爆炸样式
  • /themes/next/source/js/src/中新建fireworks.js,其中写入的代码如下。
    "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中的<body></body>标签体内添加下面代码。

    <!-- 页面点击烟花爆炸 -->
    {% if theme.fireworks %}
    <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/fireworks.js"></script>
    {% endif %}
  • 主题配置文件 中添加如下配置:

    # Fireworks 鼠标点击烟花爆炸
    fireworks: true
自定义鼠标图片
  • themes/next/source/css/_custom/custom.styl中,添加如下代码

    // 鼠标样式
    <ul><li>{
    cursor: url("http://om8u46rmb.bkt.clouddn.com/sword2.ico"),auto!important
    }
    :active {
    cursor: url("http://om8u46rmb.bkt.clouddn.com/sword1.ico"),auto!important
    }
  • 上面的url必须是ico 图片,想要自定义图片可以自行上传七牛云获取外链(加速),也可以本地加载。我就偷懒直接用其他博主的链接了。
  • 网易云音乐添加歌单进正文页面

    怎么生成歌单的外链看这里
    然后将生成的代码加入到想要放入的位置就好了(适当调整大小)。

    <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=260 height=240 src="//music.163.com/outchain/player?type=0&id=2315300596&auto=1&height=430">
    </iframe>

    设置fork me on github

    • 在这里挑选样式并复制代码 或者这里也可以。
    • 刚才复制的代码放到themes/next/layout/_layout.swig文件中,<div class="headband"></div>的下面,并且记得herf改为自己的github地址。

    添加代码块复制按钮

    • 下载clipboard.min.js并将其放到.\themes\next\source\js\src\目录下。
    • .\themes\next\source\js\src\目录下,创建clipboard-use.js,文件内容如下:
    /*页面载入完成后,创建复制按钮*/
    !function (e, t, a) {
      /* code */
      var initCopyCode = function(){
        var copyHtml = '';
        copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
        copyHtml += '  <i class="fa fa-globe"></i><span>copy</span>';
        copyHtml += '</button>';
        $(".highlight .code pre").before(copyHtml);
        new ClipboardJS('.btn-copy', {
            target: function(trigger) {
                return trigger.nextElementSibling;
            }
        });
      }
      initCopyCode();
    }(window, document);
    
    • .\themes\next\source\css\_custom\custom.styl样式文件中添加下面代码:
    //代码块复制按钮
    .highlight{
      //方便copy代码按钮(btn-copy)的定位
      position: relative;
    }
    .btn-copy {
        display: inline-block;
        cursor: pointer;
        background-color: #eee;
        background-image: linear-gradient(#fcfcfc,#eee);
        border: 1px solid #d5d5d5;
        border-radius: 3px;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
        -webkit-appearance: none;
        font-size: 13px;
        font-weight: 700;
        line-height: 20px;
        color: #333;
        -webkit-transition: opacity .3s ease-in-out;
        -o-transition: opacity .3s ease-in-out;
        transition: opacity .3s ease-in-out;
        padding: 2px 6px;
        position: absolute;
        right: 5px;
        top: 5px;
        opacity: 0;
    }
    .btn-copy span {
        margin-left: 5px;
    }
    .highlight:hover .btn-copy{
      opacity: 1;
    }
    
    • .\themes\next\layout\_layout.swig文件中,添加引用要在<body></body>标签内:
    <!-- 代码块复制功能 -->
      <script type="text/javascript" src="/js/src/clipboard.min.js"></script>  
      <script type="text/javascript" src="/js/src/clipboard-use.js"></script>
    

    配置文章结束模板

    • \themes\next\layout\_macro文件夹中,新建passage-end-tag.swig,并且写入如下代码(当然也可以自由发挥):
    <div>
        {% if not is_index %}
            <blockquote class="blockquote-center">
            <div style="text-align:center;color: #FF5733;font-size:24px;">-------------本文结束 <i class="fa fa-heart"></i> 感谢您的时间-------------</div>
            </blockquote>
        {% endif %}
    </div>
    • 接着打开\themes\next\layout\_macro\post.swig文件,在post-body 之后, post-footer 之前添加如下代码。(在我文件大约360的位置)
        <div>
          {% if not is_index %}
            {% include 'passage-end-tag.swig' %}
          {% endif %}
        </div>
    • 最后在 主题配置文件 中添加如下配置:
    # 文章末尾添加“本文结束”标记
    passage_end_tag:
      enabled: true
    • 实现效果如本文结尾所示

    头像旋转

    • 首先打开头像选项,在 主题配置文件 中。
    in theme directory(source/images): # 你的头像
    # in site  directory(source/uploads): /uploads/avatar.gif
    avatar: # 你的头像
    • 打开\themes\next\source\css\_common\components\sidebar\sidebar-author.styl,在里面添加如下代码:
    .site-author-image {
      display: block;
      margin: 0 auto;
      padding: $site-author-image-padding;
      max-width: $site-author-image-width;
      height: $site-author-image-height;
      border: $site-author-image-border-width solid $site-author-image-border-color;
      /* 头像圆形 */
      border-radius: 80px;
      -webkit-border-radius: 80px;
      -moz-border-radius: 80px;
      box-shadow: inset 0 -1px 0 #333sf;
      /* 设置循环动画 [animation: (play)动画名称 (2s)动画播放时长单位秒或微秒 (ase-out)动画播放的速度曲线为以低速结束
        (1s)等待1秒然后开始动画 (1)动画播放次数(infinite为循环播放) ]*/
    
      /* 鼠标经过头像旋转360度 */
      -webkit-transition: -webkit-transform 1.0s ease-out;
      -moz-transition: -moz-transform 1.0s ease-out;
      transition: transform 1.0s ease-out;
    }
    img:hover {
      /* 鼠标经过停止头像旋转
      -webkit-animation-play-state:paused;
      animation-play-state:paused;*/
      /* 鼠标经过头像旋转360度 */
      -webkit-transform: rotateZ(360deg);
      -moz-transform: rotateZ(360deg);
      transform: rotateZ(360deg);
    }
    /* Z 轴旋转动画 */
    @-webkit-keyframes play {
      0% {
        -webkit-transform: rotateZ(0deg);
      }
      100% {
        -webkit-transform: rotateZ(-360deg);
      }
    }
    @-moz-keyframes play {
      0% {
        -moz-transform: rotateZ(0deg);
      }
      100% {
        -moz-transform: rotateZ(-360deg);
      }
    }
    @keyframes play {
      0% {
        transform: rotateZ(0deg);
      }
      100% {
        transform: rotateZ(-360deg);
      }
    }

    全站上线时间

    • /themes/next/layout/_partials/footer.swig文件尾部加上,并且修改你的上线时间。
    <span id="timeDate">载入天数...</span><span id="times">载入时分秒...</span>
    <script>
        var now = new Date();
        function createtime() {
            var grt= new Date("07/06/2018 11:11:00");//此处修改你的建站时间或者网站上线时间
            now.setTime(now.getTime()+250);
            days = (now - grt ) / 1000 / 60 / 60 / 24; dnum = Math.floor(days);
            hours = (now - grt ) / 1000 / 60 / 60 - (24 * dnum); hnum = Math.floor(hours);
            if(String(hnum).length ==1 ){hnum = "0" + hnum;} minutes = (now - grt ) / 1000 /60 - (24 * 60 * dnum) - (60 * hnum);
            mnum = Math.floor(minutes); if(String(mnum).length ==1 ){mnum = "0" + mnum;}
            seconds = (now - grt ) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);
            snum = Math.round(seconds); if(String(snum).length ==1 ){snum = "0" + snum;}
            document.getElementById("timeDate").innerHTML = "本站已安全运行 "+dnum+" 天 ";
            document.getElementById("times").innerHTML = hnum + " 小时 " + mnum + " 分 " + snum + " 秒";
        }
    setInterval("createtime()",250);
    </script>

    daovoice

    • daovoice注册账号可以得到 app_id

    • 主题配置文件 中添加如下配置

    # Online contact
    daovoice: true
    daovoice_app_id:   # 这里填你刚才获得的 app_id
    • /themes/next/layout/_partials/head.swig,添加如下代码:
    <!-- 添加DaoVioce -->
    {% if theme.daovoice %}
      <script>
      (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/0f81ff2f.js","daovoice")
      daovoice('init', {
          app_id: "{{theme.daovoice_app_id}}"
        });
      daovoice('update');
      </script>
    {% endif %}

    阅读排行榜

    • hexo n page top新建页面,编辑自动生成的index.md文件,代码如下,替换好你的leancloud账号和页面链接(一共三处)
    <div id="top"></div>
    <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
    <script>AV.initialize("leancloud_appid", "leancloud_appkey");</script>
    <script type="text/javascript">
      var time=0
      var title=""
      var url=""
      var query = new AV.Query('Counter');
      query.notEqualTo('id',0);
      query.descending('time');
      query.limit(1000);
      query.find().then(function (todo) {
        for (var i=0;i<1000;i++){
          var result=todo[i].attributes;
          time=result.time;
          title=result.title;
          url=result.url;
          // var content="<a href='"+"https://onlychristmas.github.io"+url+"'>"+title+"</a>"+"<br>"+"<font color='#fff'>"+"阅读次数:"+time+"</font>"+"<br><br>";
          var content="<p>"+"<font color='#1C1C1C'>"+"【文章热度:"+time+"℃】"+"</font>"+"<a href='"+"https://onlychristmas.github.io"+url+"'>"+title+"</a>"+"</p>";
          document.getElementById("top").innerHTML+=content
        }
      }, function (error) {
        console.log("error");
      });
    </script>
    • 本地调试不显示,重新生成上传,才能看到排序效果

    背景透明

    • 考虑到我们这么好看的动态背景,只在文章两边很小的区域展示,有点别扭,想要让它在文章后面也能显示。
    • themes\next\source\css_schemes\你设置的主题\index.styl文件中搜索background,会出现五个结果,我这里只将前两个设置为none(透明),也可以根据需求设置更多的透明。
    // =================================================
    // Desktop layout styles.
    // =================================================
    // Post blocks.
    .content-wrap {
      padding: initial;
      background: none;
      box-shadow: initial;
      border-radius: initial;
    }
    
    // Post & Comments blocks.
    .post-block {
      padding: $content-desktop-padding;
      background: none;
      box-shadow: $box-shadow-inner;
      border-radius: $border-radius-inner;
    }
    • 如果手机端背景透明,整个页面会比较凌乱,影响阅读效果。切忌保持white
    // =================================================
    // < 767px
    // =================================================
    +mobile() {
    
      // Posts in blocks.
      .content-wrap {
        padding: $content-mobile-padding;
        background: white;
      }

    high一下

    • 打开 blog\themes\next\layout\_partials\header.swig ,在<ul> ... /ul> 标签之间加入以下代码:
    <!-- 自定义High一下的功能 -->
    <li class="menu-item"> <a title="把这个链接拖到你的工具栏中,任何网页都可以High" href='javascript:(
    /*
    * Copyright (C) 2016 Never_yu (Neveryu.github.io) <[email protected]>
    * Sina Weibo (http://weibo.com/Neveryu)
    *
    * Licensed under the Apache License, Version 2.0 (the "License");
    * you may not use this file except in compliance with the License.
    * You may obtain a copy of the License at
    *
    *      http://www.apache.org/licenses/LICENSE-2.0
    *
    * Unless required by applicable law or agreed to in writing, software
    * distributed under the License is distributed on an "AS IS" BASIS,
    * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    * See the License for the specific language governing permissions and
    * limitations under the License.
    */
    function go() {
    
    
    var songs = [
         "http://bdyun.65dj.com:8090/2015/06/28/84791C997D8C55023DAD0D5690E48C28/%D1%A6%D6%AE%C7%AB%20-%20%D1%DD%D4%B1.mp3",
         "http://7xoiki.com1.z0.glb.clouddn.com/Music-sunburst.mp3",
         ""
    ];
    
    
    function c() {
    var e = document.createElement("link");
    e.setAttribute("type", "text/css");
    e.setAttribute("rel", "stylesheet");
    e.setAttribute("href", f);
    e.setAttribute("class", l);
    document.body.appendChild(e)
    }
    
    function h() {
    var e = document.getElementsByClassName(l);
    for (var t = 0; t < e.length; t++) {
     document.body.removeChild(e[t])
    }
    }
    
    function p() {
    var e = document.createElement("div");
    e.setAttribute("class", a);
    document.body.appendChild(e);
    setTimeout(function() {
     document.body.removeChild(e)
    }, 100)
    }
    
    function d(e) {
    return {
     height : e.offsetHeight,
     width : e.offsetWidth
    }
    }
    
    function v(i) {
    var s = d(i);
    return s.height > e && s.height < n && s.width > t && s.width < r
    }
    
    function m(e) {
    var t = e;
    var n = 0;
    while (!!t) {
     n += t.offsetTop;
     t = t.offsetParent
    }
    return n
    }
    
    function g() {
    var e = document.documentElement;
    if (!!window.innerWidth) {
     return window.innerHeight
    } else if (e && !isNaN(e.clientHeight)) {
     return e.clientHeight
    }
    return 0
    }
    
    function y() {
    if (window.pageYOffset) {
     return window.pageYOffset
    }
    return Math.max(document.documentElement.scrollTop, document.body.scrollTop)
    }
    
    function E(e) {
    var t = m(e);
    return t >= w && t <= b + w
    }
    
    function S() {
    var e = document.getElementById("audio_element_id");
    if(e != null){
     var index = parseInt(e.getAttribute("curSongIndex"));
     if(index > songs.length - 2) {
         index = 0;
     } else {
         index++;
     }
     e.setAttribute("curSongIndex", index);
     N();
    }
    
    e.src = i;
    e.play()
    }
    
    function x(e) {
    e.className += " " + s + " " + o
    }
    
    function T(e) {
    e.className += " " + s + " " + u[Math.floor(Math.random() * u.length)]
    }
    
    function N() {
    var e = document.getElementsByClassName(s);
    var t = new RegExp("\\b" + s + "\\b");
    for (var n = 0; n < e.length; ) {
     e[n].className = e[n].className.replace(t, "")
    }
    }
    
    function initAudioEle() {
    var e = document.getElementById("audio_element_id");
    if(e === null){
     e = document.createElement("audio");
     e.setAttribute("class", l);
     e.setAttribute("curSongIndex", 0);
     e.id = "audio_element_id";
     e.loop = false;
     e.bgcolor = 0;
     e.addEventListener("canplay", function() {
     setTimeout(function() {
         x(k)
     }, 500);
     setTimeout(function() {
         N();
         p();
         for (var e = 0; e < O.length; e++) {
             T(O[e])
         }
     }, 15500)
    }, true);
    e.addEventListener("ended", function() {
     N();
     h();
     go();
    }, true);
    e.innerHTML = " <p>If you are reading this, it is because your browser does not support the audio element. We recommend that you get a new browser.</p> <p>";
    document.body.appendChild(e);
    }
    }
    
    initAudioEle();
    var e = 30;
    var t = 30;
    var n = 350;
    var r = 350;
    
    var curSongIndex = parseInt(document.getElementById("audio_element_id").getAttribute("curSongIndex"));
    var i = songs[curSongIndex];
    
    var s = "mw-harlem_shake_me";
    var o = "im_first";
    var u = ["im_drunk", "im_baked", "im_trippin", "im_blown"];
    var a = "mw-strobe_light";
    
    /* harlem-shake-style.css,替换成你的位置,也可以直接使用://s3.amazonaws.com/moovweb-marketing/playground/harlem-shake-style.css */
    var f = "//s3.amazonaws.com/moovweb-marketing/playground/harlem-shake-style.css";
    
    var l = "mw_added_css";
    var b = g();
    var w = y();
    var C = document.getElementsByTagName("*");
    var k = null;
    for (var L = 0; L < C.length; L++) {
    var A = C[L];
    if (v(A)) {
     if (E(A)) {
         k = A;
         break
     }
    }
    }
    if (A === null) {
    console.warn("Could not find a node of the right size. Please try a different page.");
    return
    }
    c();
    S();
    var O = [];
    for (var L = 0; L < C.length; L++) {
    var A = C[L];
    if (v(A)) {
     O.push(A)
    }
    }
    })()'><i class="menu-item-icon fa fa-music fa-fw"></i>High一下</a> </li>
    <!-- end High一下 -->
    

    添加404页面

    • blog/source/文件夹下新建404.html并加入如下代码:
    <!DOCTYPE HTML>
    <html>
    <head>
      <meta http-equiv="content-type" content="text/html;charset=utf-8;"/>
      <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
      <meta name="robots" content="all" />
      <meta name="robots" content="index,follow"/>
      <link rel="stylesheet" type="text/css" href="https://qzone.qq.com/gy/404/style/404style.css">
    </head>
    <body>
      <script type="text/plain" src="http://www.qq.com/404/search_children.js"
              charset="utf-8" homePageUrl="https://onlychristmas.github.io/"
              homePageName="回到我的主页">
      </script>
      <script src="https://qzone.qq.com/gy/404/data.js" charset="utf-8"></script>
      <script src="https://qzone.qq.com/gy/404/page.js" charset="utf-8"></script>
    </body>
    </html>

    Hexo博客操作优化

    调试优化
    • blog/package.json中并列"dependencies": {}添加如下代码:
      "scripts": {
        "dev": "hexo clean && hexo generate && hexo server --debug"
      }
    • 现在我们只需 npm run dev 一条命令就可以启动本地的调试环境
    博客内容压缩
    • blog/package.json"dependencies": {}后面平行的添加如下内容:
    "devDependencies": {
      "gulp-asset-rev": "^0.0.15",
      "gulp-clean-css": "^3.9.0",
      "gulp-concat": "^2.6.1",
      "gulp-debug": "^3.1.0",
      "gulp-htmlclean": "^2.7.15",
      "gulp-htmlmin": "^3.0.0",
      "gulp-if": "^2.0.2",
      "gulp-changed": "^3.1.0",
      "gulp-make-css-url-version": "^0.0.13",
      "gulp-modify-css-urls": "^0.2.2",
      "gulp-plumber": "^1.1.0",
      "gulp-uglify": "^3.0.0",
      "gulp-useref": "^3.1.2",
      "gulp-util": "^3.0.8",
    
      "hexo-deployer-git": "^0.3.1",
      "hexo-encrypt": "^0.5.1",
      "hexo-generator-json-content": "^3.0.1",
      "hexo-generator-search": "^2.1.1",
      "hexo-generator-searchdb": "^1.0.8",
      "hexo-server": "^0.2.2",
      "run-sequence": "^2.2.0"
    }
    • 然后输入以下命令安装依赖包
    npm config set registry https://registry.npm.taobao.org
    npm install
    • blog/gulpfile.js中添加如下代码(没有的话则新建):
    /*  npm install 超时请使用:(两条命令在当前文件目录下执行)
       npm config set registry https://registry.npm.taobao.org
       npm install
       或者:
       npm install -g cnpm --registry=https://registry.npm.taobao.org
       cnpm install
    */
    var gulp = require('gulp');
    var debug = require('gulp-debug');
    var cleancss = require('gulp-clean-css');   //css压缩组件
    var cssversion = require('gulp-make-css-url-version');   //css资源添加版本号
    var uglify = require('gulp-uglify');        //js压缩组件
    var htmlmin = require('gulp-htmlmin');      //html压缩组件
    var htmlclean = require('gulp-htmlclean');  //html清理组件
    var assetRev = require('gulp-asset-rev');   //版本控制插件
    var runSequence = require('run-sequence');  //异步执行组件
    var changed = require('gulp-changed');      //文件更改校验组件
    var gulpif = require('gulp-if')             //任务 帮助调用组件
    var plumber = require('gulp-plumber');      //容错组件(发生错误不跳出任务,并报出错误内容)
    var isScriptAll = true;     //是否处理所有文件,(true|处理所有文件)(false|只处理有更改的文件)
    var isDebug = true;         //是否调试显示 编译通过的文件
    // 压缩js文件
    gulp.task('compressJs', function () {
        var option = {
            // preserveComments: 'all',//保留所有注释
            mangle: true,           //类型:Boolean 默认:true 是否修改变量名
            compress: true          //类型:Boolean 默认:true 是否完全压缩
        }
        return gulp.src(['./public/**/*.js','!./public/**/*.min.js'])  //排除的js
            .pipe(gulpif(!isScriptAll, changed('./public')))
            .pipe(gulpif(isDebug,debug({title: 'Compress JS:'})))
            .pipe(plumber())
            .pipe(uglify(option))                //调用压缩组件方法uglify(),对合并的文件进行压缩
            .pipe(gulp.dest('./public'));         //输出到目标目录
    });
    // 压缩css文件
    gulp.task('compressCss', function () {
        return gulp.src('./public/**/*.css')
            .pipe(gulpif(!isScriptAll, changed('./public')))
            .pipe(gulpif(isDebug,debug({title: 'Compress CSS:'})))
            .pipe(plumber())
            .pipe(cleancss({rebase: false}))
            .pipe(gulp.dest('./public'));
    });
    // 压缩html文件
    gulp.task('compressHtml', function () {
        var cleanOptions = {
            protect: /<\!--%fooTemplate\b.*?%-->/g,             //忽略处理
            unprotect: /<script [^>]*\btype="text\/x-handlebars-template"[\s\S]+?<\/script>/ig //特殊处理
        }
        var minOption = {
            collapseWhitespace: true,           //压缩HTML
            collapseBooleanAttributes: true,    //省略布尔属性的值  <input checked="true"/> ==> <input />
            removeEmptyAttributes: true,        //删除所有空格作属性值    <input id="" /> ==> <input />
            removeScriptTypeAttributes: true,   //删除<script>的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'));
    });
    // 默认任务
    gulp.task('default', function () {
        runSequence.options.ignoreUndefinedTasks = true;
        runSequence('compressHtml','compressCss','compressJs');
    });
    
    • 然后我们的上传命令就变成了
    hexo g
    gulp
    hexo d

    其实还可以继续偷懒,没办法,就是懒人才能改变世界……在刚才添加的`”devDependencies”: {}`后面平行的添加如下代码

      "scripts": {
        "submit": "hexo clean && hexo generate && gulp && hexo d"
      }

    这样之后,上传就变为了一条命令`npm run sumbit`

    自动打开脚本
    • 为了每次新建博文我们可以直接编辑,而不是在一堆文件中找到它再打开。我们需要在博客根目录新建script文件夹(已有就不用新建)
    • 在新建的文件夹新建一个.js文件,其中填写的代码如下所示。代码来自这里
      win用户
    var spawn = require('child_process').exec;
    
    // Hexo 2.x 用户复制这段
    hexo.on('new', function(path){
      spawn('start  "markdown编辑器绝对路径.exe" ' + path);
    });
    
    // Hexo 3 用户复制这段
    hexo.on('new', function(data){
      spawn('start  "markdown编辑器绝对路径.exe" ' + data.path);
    });

    Mac用户

    var exec = require('child_process').exec;
    
    // Hexo 2.x 用户复制这段
    hexo.on('new', function(path){
        exec('open -a "markdown编辑器绝对路径.app" ' + path);
    });
    // Hexo 3 用户复制这段
    hexo.on('new', function(data){
        exec('open -a "markdown编辑器绝对路径.app" ' + data.path);
    });
    仓库备份博客
    • 依次执行下列命令
    git init  # 初始化仓库
    git remote add origin git@github.com # 从仓库复制你的地址 .git
    git pull origin master    
    • /blog/目录下新建.gitignore文件(如果没有的话),里面内容如下。主要是为了忽略./public等无需备份的文件,加快备份速度。
    .DS_Store
    Thumbs.db
    db.json
    *.log
    node_modules/
    public/
    .deploy*/
    • 本地写完博客上传后,只要依次运行下列命令就可以备份文件。
    git add .
    git commit -m "更新hexo源文件"
    git push origin master
    • 当远程仓库有更新时,执行以下命令,即可同步hexo源文件到本地。
    git pull origin master
    • 在你的其他电脑,只要git clone [email protected] #你的仓库地址就可以同步博客文件了。
    自动备份博客脚本
    • 程序员在变懒这件事情上绝对有着永无止境的追求!我们不仅会担心博客本地源文件的丢失,还会烦恼多台电脑文件同步困难。那么我们怎么解决这样的困境呢?
    • npm install --save shelljs安装这个模块
    • /blog/scripts/文件夹下新建一个js脚本(任意名字),如果没有/blog/scripts/目录,请新建一个。脚本内容如下:更改第十七行的内容
    require('shelljs/global');
    
    try {
        hexo.on('deployAfter', function() {//当deploy完成后执行备份
            run();
        });
    } catch (e) {
        console.log("产生了一个错误<( ̄3 ̄)> !,错误详情为:" + e.toString());
    }
    
    function run() {
        if (!which('git')) {
            echo('Sorry, this script requires git');
            exit(1);
        } else {
            echo("======================Auto Backup Begin===========================");
            cd('####你的地址');    //此处修改为博客根目录路径
            if (exec('git add --all').code !== 0) {
                echo('Error: Git add failed');
                exit(1);
    
            }
            if (exec('git commit -am "Form auto backup script\'s commit"').code !== 0) {
                echo('Error: Git commit failed');
                exit(1);
    
            }
            if (exec('git push origin master').code !== 0) {
                echo('Error: Git push failed');
                exit(1);
    
            }
            echo("==================Auto Backup Complete============================")
        }
    }
    • 这样在每次hexo d命令之后就能自动备份博客到设置好的代码仓库。成功后会显示如下类似内容

    INFO  Deploy done: git
    ======================Auto Backup Begin===========================
    [master cea81b4] Form auto backup script's commit
     1 file changed, 1 insertion(+), 1 deletion(-)
    To #你的仓库地址
       8f2653b..cea81b4  master -> master
    ==================Auto Backup Complete============================

    跳动的心

    • 站点配置文件 配置如下信息:
    footer:
      icon: heart
    • 打开 /blog/themes/next/layout/_partials/footer.swig文件, 将 <span class="with-love">换成下面代码:
    <span class="with-love" id="heart">
    • 打开/blog/themes/next/source/css/_custom/custom.styl文件,下面代码(颜色可以自定义):
    // 自定义页脚跳动的心样式
    @keyframes heartAnimate {
        0%,100%{transform:scale(1);}
        10%,30%{transform:scale(0.9);}
        20%,40%,60%,80%{transform:scale(1.1);}
        50%,70%{transform:scale(1.1);}
    }
    #heart {
        animation: heartAnimate 1.33s ease-in-out infinite;
    }
    .with-love {
        color: rgb(255, 113, 168);
    }

    博客自定义写作样式

    • 这里从neveryu的建站日志引用部分代码,放入到themes/next/source/css/_custom/custom.styl中,即可生效。
    // 下载样式
    a#download {
      display: inline-block;
      padding: 0 10px;
      color: #000;
      background: transparent;
      border: 2px solid #000;
      border-radius: 2px;
      transition: all .5s ease;
      font-weight: bold;
      &:hover {
        background: #000;
        color: #fff;
      }
    }
    
    //阅读全文样式
    .post-more-link .btn {
      position:relative;
      border: 2px solid #000;
      border-radius: 2px;
      padding: 0 10px;
      font-weight: bold;
      background: transparent;
      transition: all .5s ease;
      &:hover {
        background: #000;
        color: #eee;
      }
    }
    //
    
    // 颜色块-黄
    span#inline-yellow {
      display:inline;
      padding:.2em .6em .3em;
      font-size:80%;
      font-weight:bold;
      line-height:1;
      color:#fff;
      text-align:center;
      white-space:nowrap;
      vertical-align:baseline;
      border-radius:0;
      background-color: #f0ad4e;
    }
    // 颜色块-黑
    span#inline-black {
      display:inline;
      padding:.2em .6em .3em;
      font-size:80%;
      font-weight:bold;
      line-height:1;
      color:#fff;
      text-align:center;
      white-space:nowrap;
      vertical-align:baseline;
      border-radius:0;
      background-color: black;
    }
    // 颜色块-绿
    span#inline-green {
      display:inline;
      padding:.2em .6em .3em;
      font-size:80%;
      font-weight:bold;
      line-height:1;
      color:#fff;
      text-align:center;
      white-space:nowrap;
      vertical-align:baseline;
      border-radius:0;
      background-color: #5cb85c;
    }
    // 颜色块-蓝
    span#inline-blue {
      display:inline;
      padding:.2em .6em .3em;
      font-size:80%;
      font-weight:bold;
      line-height:1;
      color:#fff;
      text-align:center;
      white-space:nowrap;
      vertical-align:baseline;
      border-radius:0;
      background-color: #2780e3;
    }
    // 颜色块-紫
    span#inline-purple {
      display:inline;
      padding:.2em .6em .3em;
      font-size:80%;
      font-weight:bold;
      line-height:1;
      color:#fff;
      text-align:center;
      white-space:nowrap;
      vertical-align:baseline;
      border-radius:0;
      background-color: #9954bb;
    }
    // 颜色块-红
    span#inline-red {
      display:inline;
      padding:.2em .6em .3em;
      font-size:80%;
      font-weight:bold;
      line-height:1;
      color:#fff;
      text-align:center;
      white-space:nowrap;
      vertical-align:baseline;
      border-radius:0;
      background-color: #df3e3e;
    }
    
    // 左侧边框红色块级
    p#div-border-left-red {
      display: block;
      padding: 10px;
      margin: 10px 0;
      border: 1px solid #ccc;
      border-left-width: 5px;
      border-radius: 3px;
      border-left-color: #df3e3e;
    }
    // 左侧边框黄色块级
    p#div-border-left-yellow {
      display: block;
      padding: 10px;
      margin: 10px 0;
      border: 1px solid #ccc;
      border-left-width: 5px;
      border-radius: 3px;
      border-left-color: #f0ad4e;
    }
    // 左侧边框绿色块级
    p#div-border-left-green {
      display: block;
      padding: 10px;
      margin: 10px 0;
      border: 1px solid #ccc;
      border-left-width: 5px;
      border-radius: 3px;
      border-left-color: #5cb85c;
    }
    // 左侧边框蓝色块级
    p#div-border-left-blue {
      display: block;
      padding: 10px;
      margin: 10px 0;
      border: 1px solid #ccc;
      border-left-width: 5px;
      border-radius: 3px;
      border-left-color: #2780e3;
    }
    // 左侧边框紫色块级
    p#div-border-left-purple {
      display: block;
      padding: 10px;
      margin: 10px 0;
      border: 1px solid #ccc;
      border-left-width: 5px;
      border-radius: 3px;
      border-left-color: #9954bb;
    }
    // 右侧边框红色块级
    p#div-border-right-red {
      display: block;
      padding: 10px;
      margin: 10px 0;
      border: 1px solid #ccc;
      border-right-width: 5px;
      border-radius: 3px;
      border-right-color: #df3e3e;
    }
    // 右侧边框黄色块级
    p#div-border-right-yellow {
      display: block;
      padding: 10px;
      margin: 10px 0;
      border: 1px solid #ccc;
      border-right-width: 5px;
      border-radius: 3px;
      border-right-color: #f0ad4e;
    }
    // 右侧边框绿色块级
    p#div-border-right-green {
      display: block;
      padding: 10px;
      margin: 10px 0;
      border: 1px solid #ccc;
      border-right-width: 5px;
      border-radius: 3px;
      border-right-color: #5cb85c;
    }
    // 右侧边框蓝色块级
    p#div-border-right-blue {
      display: block;
      padding: 10px;
      margin: 10px 0;
      border: 1px solid #ccc;
      border-right-width: 5px;
      border-radius: 3px;
      border-right-color: #2780e3;
    }
    // 右侧边框紫色块级
    p#div-border-right-purple {
      display: block;
      padding: 10px;
      margin: 10px 0;
      border: 1px solid #ccc;
      border-right-width: 5px;
      border-radius: 3px;
      border-right-color: #9954bb;
    }
    // 上侧边框红色
    p#div-border-top-red {
      display: block;
      padding: 10px;
      margin: 10px 0;
      border: 1px solid #ccc;
      border-top-width: 5px;
      border-radius: 3px;
      border-top-color: #df3e3e;
    }
    // 上侧边框黄色
    p#div-border-top-yellow {
      display: block;
      padding: 10px;
      margin: 10px 0;
      border: 1px solid #ccc;
      border-top-width: 5px;
      border-radius: 3px;
      border-top-color: #f0ad4e;
    }
    // 上侧边框绿色
    p#div-border-top-green {
      display: block;
      padding: 10px;
      margin: 10px 0;
      border: 1px solid #ccc;
      border-top-width: 5px;
      border-radius: 3px;
      border-top-color: #5cb85c;
    }
    // 上侧边框蓝色
    p#div-border-top-blue {
      display: block;
      padding: 10px;
      margin: 10px 0;
      border: 1px solid #ccc;
      border-top-width: 5px;
      border-radius: 3px;
      border-top-color: #2780e3;
    }
    // 上侧边框紫色
    p#div-border-top-purple {
      display: block;
      padding: 10px;
      margin: 10px 0;
      border: 1px solid #ccc;
      border-top-width: 5px;
      border-radius: 3px;
      border-top-color: #9954bb;
    }
    
    //动画模块
    //第一篇博客中-精于心,简于形-的动画(https://neveryu.github.io/page/2/)
    span#top-down-samll {
      display:inline;
      position:relative;
      border-top:1px solid #222;
      border-bottom:1px solid #222;
      font-size:110%;
      cursor:pointer;
      &:hover {
        background-color: #000;
        color: #fff;
        animation: animate-yu-1 3s ease-in;
      }
    }
    @keyframes animate-yu-1 {
      0% {
        left:-10px;
        top:0px;
      }
      10% {
        left:10px;
        top:0px;
      }
      20% {
        left:-8px;
        top:0px;
      }
      30% {
        left:8px;
        top:0px;
      }
      40% {
        left:-5px;
        top:0px;
      }
      50% {
        left:5px;
        top:0px;
      }
      60% {
        left:-3px;
        top:0px;
      }
      70% {
        left:3px;
        top:0px;
      }
      80% {
        left:-1px;
        top:0px;
      }
      90% {
        left:1px;
        top:0px;
      }
      100% {
        left:0px;
        top:0px;
      }
    }
    //留言页面-[最近访客]-的样式
    span#top-down {
      display:inline;
      position:relative;
      border-top:1px solid #222;
      border-bottom:1px solid #222;
      font-size:130%;
    }

    写作辅助


    新建文件类型

    • hexo new post "title" 用来创建新文章
    • hexo new page "title" 用来创建新菜单页面
    • hexo new draft "title" 用来创建新草稿
    • hexo new "title" 用来创建新文章(默认)

    关于目录

    • 目录的层级靠#######来维护,相差几个#就是相差几级的目录。
    • 目录的最高层级为##

    主题自带样式 note 标签

    首先要在 站点配置文件 配置如下信息:

    # Note tag (bs-callout).
    note:
      # Note tag style values:
      #  - simple    bs-callout old alert style. Default.
      #  - modern    bs-callout new (v2-v3) alert style.
      #  - flat      flat callout style with background, like on Mozilla or StackOverflow.
      #  - disabled  disable all CSS styles import of note tag.
      style: flat
      icons: true
      border_radius: 3
      # Offset lighter of background in % for modern and flat styles (modern: -12 | 12; flat: -18 | 6).
      # Offset also applied to label tag variables. This option can work with disabled note tag.
      light_bg_offset: 0

    这是每种样式的调用方式 `

    default

    `

    这是每种样式的调用方式 `

    primary

    `

    这是每种样式的调用方式 `

    success

    `

    这是每种样式的调用方式 `

    info

    `

    这是每种样式的调用方式 `

    warning

    `

    这是每种样式的调用方式 `

    danger

    `

    这是每种样式的调用方式 `

    danger no-icon

    `

    自定义数字块

    • ~/themes/next/source/css/_custom/custom.styl中添加下列代码:
    // 自定义的数字块
        span#inline-toc {
        display: inline-block;
        border-radius: 80% 100% 90% 20%;
        background-color: rgb(227, 242, 253);
        color: #555;
        padding: 0.05em 0.4em;
        margin: 2px 5px 2px 0px;
        line-height: 1.5;
    }
    • 这是调用方式<span id="inline-toc">1.</span>和样式展示 1.

    自定义颜色块

    自定义的颜色块标签,这么用: yellowblackgreenblueredpurple

    <span id="inline-purple">颜色块标签内容</span>

    块级框该这么用(自定义的比Next主题内置的优化要更加清晰好用):

    上侧块级框总共5个类型

    类似的,侧边块级框比颜色块少一个黑色,分左右两种,总共十个类型

    <p id='div-border-left-red'>  </p>

    文字的上下加横线

    <span id="top-down">文字的上下加横线</span>

    鼠标放这里有惊喜

    <span id="top-down-samll">小一号文字,上下加横线</span>

    文本居中

    {% cq %}
    人生乃是一面镜子,
    从镜子里认识自己,
    我要称之为头等大事,
    也只是我们追求的目的!
    {% endcq %}

    {% cq %}
    人生乃是一面镜子,
    从镜子里认识自己,
    我要称之为头等大事,
    也只是我们追求的目的!
    {% endcq %}

    参考文献

    猜你喜欢

    转载自blog.csdn.net/huhehaotechangsha/article/details/80489544