本文详细介绍了如何在Butterfly主题版本3.8.0及以上中创建一个数字时钟功能。首先,在JavaScript文件中,通过创建数组和时间结构,构建了时钟的数字和小时、分钟、秒钟的表示。接着,使用DOM操作创建了时钟的容器和数字组,并为每个数字添加了相应的类名。在CSS文件中,定义了时钟的样式,包括字体大小、位置、间距和动画效果。此外,通过修改widget.yml文件,可以控制时钟显示的位置和排序。最后,针对使用Gulp压缩资源可能导致的问题,提供了在gulpfile.js中排除特定文件的解决方案,确保时钟功能的正常运行。
样式展示
创建[themes]/source/js/custom/digit-clock.js文件,在其中添加如下内容:
js
var _time10 = Array.from(Array(10)).map((n, i) => i);
var _time6 = _time10.slice(0, 6);
var _time3 = _time10.slice(0, 3);
var _Structure = [
[_time3, _time10],
[_time6, _time10],
[_time6, _time10]
];
var clock = document.createElement('div');
clock.id = 'clock';
document.getElementById("digit-clock").appendChild(clock);
var digitGroups = [];
requestAnimationFrame(update);
_Structure.forEach(digits => {
var digitGroup = document.createElement('div');
digitGroup.classList.add('digit-group');
clock.appendChild(digitGroup);
digitGroups.push(digitGroup);
digits.forEach(digitList => {
var digit = document.createElement('div');
digit.classList.add('digit');
digitList.forEach(n => {
var ele = document.createElement('div');
ele.classList.add('digit-number');
ele.innerText = n;
digit.appendChild(ele);
});
digitGroup.appendChild(digit);
});
});
function update() {
requestAnimationFrame(update);
var date = new Date();
var time = [date.getHours(), date.getMinutes(), date.getSeconds()].
map(n => `0${n}`.slice(-2).split('').map(e => +e)).
reduce((p, n) => p.concat(n), []);
time.forEach((n, i) => {
var digit = digitGroups[Math.floor(i * 0.5)].children[i % 2].children;
Array.from(digit).forEach((e, i2) => e.classList[i2 === n ? 'add' : 'remove']('bright'));
});
}
创建[themes]/source/css/custom/digit-clock.css文件,在其中添加如下内容:
css
#digit-clock {
display: flex;
justify-content: center;
align-items: center;
}
#clock {
font-size: 10px;
position: relative;
}
.digit-group {
display: inline-block;
}
.digit-group:not(:last-child):after {
color: inherit;
content: ":";
font-size: 50px;
}
.digit {
display: inline-block;
width: 33px;
}
.digit .digit-number {
color: inherit;
transform: rotate(-90deg);
transition: font-size 200ms,transform 350ms,color 150ms;
}
.digit .digit-number.bright {
color: inherit;
font-size: 25px;
transform: rotate(0deg);
}
创建[blog]/source/_data/widget.yml文件,添加如下内容:
yml
top:
- class_name: card-clock
id_name:
name:
icon:
order:
html: <div id="digit-clock"></div><script defer async data-pjax src="/js/custom/digit-clock.js"></script>
假如你想除了文章页面都显示时钟就将top改成bottom
可以通过修改order的值来为你的侧边栏进行排序
假如你使用gulp压缩资源,可能会导致无法运行,修改gulpfile.js(我这里是使用的空梦的gulp):
js
gulp.task('minify-js', () =>
gulp.src(['./public/**/*.js','!./public/**/digit-clock.js'])
.pipe(terser({
compress: {
sequences: 50,
unsafe: true,
unsafe_math: true,
pure_getters: true,
ecma: true
}
}))
.pipe(gulp.dest('./public'))
)
我们可以在gulp.src中添加一个!./public/path/to/your/file.js来排除某个文件。这意味着 Gulp 将会处理./public/**/*.js匹配的所有文件,除了./public/path/to/your/file.js。