前言
- 本次主要实现的功能是指定组件插入特定文本,并以打字的方式出现。主要是通过使用JavaScript插件
typed
和jquery
实现 - 使用本教程之前记得先将博客备份,以免出现不可逆损失
- Hexo版本:4.2.0
- NexT版本:7.7.1
- typed版本:2.0.4
具体步骤
1)下载插件
本次使用的typed
插件下载地址:https://cdn.bootcss.com/typed.js/2.0.5/typed.js,jquery
插件下载地址:https://wow.techbrood.com/libs/jquery/jquery.min.js
在使用浏览器下载时,可以通过Ctrl+s组合键将其保存为.js文件
下载完成之后将此插件放入Hexo根目录的source
文件夹的某个路径下,为了便于引用,我直接存放在source
文件夹下
2)创建swig文件
typewriter.swig:先在Hexo根目录的themes\next\layout
路径下创建.swig
文件,此文件主要用于存放将要加入index.html页面中的代码。本次创建的文件名为typewriter.swig
,其中代码主要为:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="typed.js"></script>
<script>
var typed = new Typed('.typewriter-content',{
// 注意:输出的可以是标签,将标签当节点运行.比如下面的h1
// 这是一个字符串数组,可以填充多个值,使用引号修饰,使用逗号分割
strings: ['<h1>{{ subtitle }}<h1>'],
// 速度值越小打字速度越快
typeSpeed:80,
// 用于在在输出字符结尾闪烁的符号
cursorChar: '_'
});
// 设置页面加载完成时再开始打字
typed.stop();
$(document).ready(function () {
typed.start();
});
</script>
参数介绍:typewriter-content
是需要插入打字动画的组件的class名,{{subtitle}}
指的是Hexo根目录_config.yml
文件中自定义设置的subtitle变量即副标题,此参数可以直接手动设置成其他字符串
也可以使用下载地址的方式引入插件,如:
script src="//wow.techbrood.com/libs/jquery/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.bootcss.com/typed.js/2.0.5/typed.js"></script>
可以在浏览器中使用开发者模式(F12)来查看各个组件的class ID,如:
<div class="typewriter-container">
<div class="typewriter">
<span class="typewriter-content"></span>
</div>
</div>
3)引入自定义的swig文件
在Hexo根目录的themes\next\layout
路径下找到index.swig
文件,此文件专门用于控制生成的index.html文件内容,遵循swig语法。在其中合适空行加入以下命令:
{# 在index.html页面加入打字动画特效 #}
{% include 'typewriter.swig' %}
4)设置CSS样式
在NexT主题目录下的_config.yml
文件中的custom_file_path
下通过设置style
参数来指定自定义CSS样式文件的路径,此文件中的样式设置会覆盖之前默认样式参数
默认路径为Hexo根目录下的source\_data\styles.styl
,此文件需要自行创建
可以通过插入以下代码来设置打字效果中游标的CSS样式:
/* 如果光标没出现,而是出现在下一行,那么就是盒子是块级标签,必须得转换成行内标签 */
h1 {
display: inline;
font-size: 3rem!important;
}
/* 想让的光标闪动的话,复制下面的代码 */
.typed-cursor{
opacity: 1;
font-size: 3rem!important;
animation: typedjsBlink 1s infinite;
-webkit-animation: typedjsBlink 1s infinite;
}
@keyframes typedjsBlink{
50% { opacity: 0.0; }
}
@-webkit-keyframes typedjsBlink{
0% { opacity: 1; }
50% { opacity: 0.0; }
100% { opacity: 1; }
}
.typed-fade-out{
opacity: 0;
transition: opacity .25s;
-webkit-animation: 0;
animation: 0;
}
5)重新生成博客
hexo clean && hexo g && hexo s