准备工作

这边使用Pjax来实现页面的动画。Butterfly内置了Pjax插件,直接在 /themes/butterfly/_config.yml 中搜索Pjax,然后把 enable 选项改成 true,如下所示:

# https://github.com/MoOx/pjax
pjax:
enable: true
# Exclude the specified pages from pjax, such as '/music/'
exclude:
# - /xxxxxx/

步骤

首先,在 /themes/butterfly/source/css 下创建 custom.css 写入如下代码:

/* 默认(白天模式) */
body {
background-color: white;
color: black;
}

[data-theme="dark"] body {
background-color: #121212;
color: white;
}

.pjax-leave-active {
opacity: 0;
background-color: inherit;
/* 使用继承的背景色 */
}

.pjax-enter-active {
transition: opacity 1s cubic-bezier(0.22, 0.61, 0.36, 1), background-color 1s ease-in-out, transform 1s ease-in-out;
opacity: 1;
background-color: inherit;
/* 使用继承的背景色 */
}

然后,在 /themes/butterfly/source/js 下创建 custom.js 写入如下代码:

document.addEventListener('DOMContentLoaded', function () {
if (window.Pjax) {
new Pjax({
elements: 'a',
selectors: ['title', '.content'],
cacheBust: false
});

document.addEventListener('pjax:send', function () {
document.body.classList.add('pjax-leave-active');
});

document.addEventListener('pjax:complete', function () {
document.body.classList.remove('pjax-leave-active');
document.body.classList.add('pjax-enter-active');
setTimeout(function () {
document.body.classList.remove('pjax-enter-active');
}, 500);
});
}

// 切换主题的示例代码
const toggleThemeButton = document.getElementById('toggle-theme');
toggleThemeButton.addEventListener('click', function () {
const htmlElement = document.documentElement;
const currentTheme = htmlElement.getAttribute('data-theme');
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
htmlElement.setAttribute('data-theme', newTheme);
});
});

最后,在 /themes/butterfly/_config.yml 中搜索 inject,或者直接在外部的 _config.butterfly.yml 里面添加如下代码:

inject:
head:
- <link rel="stylesheet" href="/css/custom.css">
bottom:
- <script src="/js/custom.js"></script>

调试动画

调试的时候,可以直接在浏览器的 F12 下修改动画效果,也就是 cubic-bezier(0.22, 0.61, 0.36, 1) 贝塞尔曲线,可以直接看见图片:

Image 5