前言

没错!我又在实验室摸鱼了,无心科研,想来想去干点什么好呢?突然想到早上吃饭时候凡哥和我说今天是国家公祭日,想着给博客整个黑白特效,整起!

全局黑白效果

hexo + butterfly 全局黑白代码

html
  body
    // 黑白色
    style.
      html{
      filter: grayscale( 100%);
      -webkit-filter: grayscale( 100%);
      -moz-filter: grayscale( 100%);
      -ms-filter: grayscale( 100%);
      -o-filter: grayscale( 100%);
      filter: url( "data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
      filter:progid:DXImageTransform.Microsoft.BasicImage(grayscale=1);
      -webkit-filter: grayscale( 1);
      }

然后把这一串代码存到一个名为blackandwhite.pug的文件,将它放在主题目录下的layout/includes/addons里面,然后就要在layout.pug 里面引入文件。在原文件的include ./head.pug下面加入一行来引入我们的文件

if theme.blackandwhite
  include ./addons/blackandwhite.pug

在主题配置文件中加一行

blackandwhite: true

效果图:

实现了这一步后可以手动开关全局黑白特效,但能不能在清明和国家公祭日自动开启全局黑呢?理论上是可行的,在主题配置文件中设置日期,在上面if theme.blackandwhite加入读取当前日期与设定日期判断的逻辑,就可以实现特定日期自动全局黑白。理论可行,实践开始!

对于前端来说,可谓是一窍不通,第一步得知道layout.pug代码是什么语言/(ㄒoㄒ)/~~,直接问ChatGPT。

先用js实现一下日期判等

var d = new Date()
var current = d.toLocaleDateString()
var date1 = "12-13"
var date2 = "04-04"
var currentDate = current.slice(5)
var result = date1.replace(/\-/g,'/') ===currentDate;
console.log(currentDate);
console.log(date1.replace(/\-/g,'/'));
console.log(result);

pug文件中加入JS

在pug文件中,js代码前面要加一个 “ - ”

  • 踩了一个小坑

hexo的pug文件里日期的输出是反过来的,所以上面截取后5个字符串的代码输出为“/2023”报错,改成截取字符串前五个

layout.pug文件中include ./head.pug后加入一下代码:

- var currentDate = new Date().toLocaleDateString().slice(0,5)
- var date1 = "12/13" === currentDate
- var date2 = "04/04" === currentDate
   

if theme.blackandwhite
  if date1 || date2
    include ./addons/blackandwhite.pug

会自动判断当前日期是否为“12/13”、“04/04”,自动开启全局黑白特效。

后记

  • 本来打算日期是写在主题配置文件里的,但是传参时候出了问题,干脆直接把日期写在代码里了。有空再解决这个问题

  • 日期判等的时候有个疑问,hexo是静态的,是否能知道当前日期是几号。最后发现是想多了,因为博客就有一个“最后更新日期”,能获得当前日期时间