效果展示
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文字特效</title>
<style>
body {
display: flex;
justify-content: center;
min-height: 100vh;
margin: 0;
align-items: center;
flex-direction: column;
}
h1 {
font-size: 6rem;
font-family: Arial, Helvetica, sans-serif;
}
span {
display: inline-block;
/* animation: 0.4s jump ease-in-out;
animation-delay: var(--delay); */
}
h1.animate span {
animation: 0.4s var(--animation) ease-in-out;
animation-delay: var(--delay);
/* 出现了莫名的bug,不简写,不生效,暂时无法得知 */
/* animation-name: var(--animation); */
/* animation-direction: .4s; */
/* animation-timing-function: ease-in-out; */
/* animation-delay: var(--delay); */
}
@keyframes jump {
0%,
100% {
transform: translateY(0px);
}
50% {
transform: translateY(-10px);
}
}
@keyframes pop {
0%,
100% {
transform: scale(1);
}
50% {
transform: scale(1.2);
}
}
@keyframes flip {
0%,
100% {
transform: rotateY(0);
}
50% {
transform: rotateY(90deg);
}
}
@keyframes blink {
0%,
100% {
color: inherit;
}
50% {
color: yellow;
}
}
@keyframes all {
0%,
100% {
color: inherit;
transform: scale(1);
transform: rotateY(0);
transform: translateY(0px);
}
50% {
color: yellow;
transform: rotateY(90deg);
transform: scale(1.2);
transform: translateY(-10px);
}
}
</style>
</head>
<body>
<h1>想起那夕阳下的奔跑,那是我逝去的青春</h1>
<!--
通过自定义属性,方便区别按钮事件
-->
<button data-animation="jump">jump</button>
<button data-animation="pop">POP</button>
<button data-animation="flip">FLIP</button>
<button data-animation="blink">BLINK</button>
<button data-animation="all">all</button>
<script>
const h1 = document.querySelector('h1')
// textContent获得元素的文本内容:
// replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。$&与 regexp 相匹配的子串。
h1.innerHTML = h1.textContent.replace(/\S/g, '<span>$&</span>')
document.querySelectorAll('span').forEach((span, index) => {
span.style.setProperty('--delay', `${index*0.1}s`)
})
document.querySelectorAll('button').forEach(button => {
button.addEventListener('click', e => {
// getAttribute() 方法返回指定属性名的属性值。
h1.style.setProperty('--animation', e.target.getAttribute('data-animation'))
// 可以让btn多触发
h1.classList.remove('animate')
// 浏览器性能问题,会导致,短时间内移除后添加的class不生效,因为页面不会重绘,则这个时候添加一个查询h1功能
// 在使用立即执行的函数表达式时,可以利用 void 运算符让 JavaScript 引擎把一个function关键字识别成函数表达式而不是函数声明(语句)。
void h1.offsetWidth
h1.classList.add('animate')
})
})
</script>
</body>
</html>
思路以及解析
通过JS给每个文字添加动态的标签
通过动画延时,给每个添加上不同的延时时间,达到视觉效果;
给每个按钮添加不同的属性,方便区别每个按钮事件,然后给按钮添加类名
给每个按钮不一样的动画名称,区别每个动画的效果
注意事项
// 浏览器性能问题,会导致,短时间内移除后添加的class不生效,因为页面不会重绘,则这个时候添加一个查询h1功能
// 在使用立即执行的函数表达式时,可以利用 void 运算符让 JavaScript 引擎把一个function关键字识别成函数表达式而不是函数声明(语句)。