实现效果
代码
<!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>
</head>
<style>
:root {
font-size: 20px;
}
body {
display: flex;
min-height: 100vh;
justify-content: center;
align-items: center;
margin: 0;
padding: 0;
}
h1 {
font-size: 6rem;
margin: 0;
padding: 0;
font-family: monospace;
position: relative;
}
h1::after {
content: '';
display: inline-block;
position: absolute;
width: 20px;
height: 6rem;
background: #000;
border-radius: 2px;
right: -30px;
}
h1 span {
--deday: 10s;
display: inline-block;
overflow: hidden;
width: 0ch;
animation: 0.1s text-in ease-in-out forwards;
animation-delay: var(--delay);
}
h1.ended::after {
animation: 1.1s typeing steps(2, jump-none) infinite;
}
@keyframes text-in {
from {
width: 0ch;
}
to {
width: 1ch;
}
}
@keyframes typeing {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
</style>
<body>
<h1>cssStudy</h1>
<script>
const h1 = document.querySelector('h1')
// 给文字添加span标签
h1.innerHTML = h1.textContent.replace(/\S/g, '<span>$&</span>')
let delay = 0
// 给动画添加延时
document.querySelectorAll('span').forEach((span, index) => {
delay += 0.1
if (index === 3) {
delay += 0.3
}
// https://developer.mozilla.org/zh-CN/docs/Web/API/CSSStyleDeclaration/setProperty
span.style.setProperty('--delay', `${delay}s`)
});
// https://www.runoob.com/jsref/event-animationend.html
h1.addEventListener('animationend', (e) => {
if (e.target === document.querySelector('h1 span:last-child')) {
h1.classList.add('ended')
}
})
</script>
</body>
</html>
var 在css中使用
var()函数可以代替元素中任何属性中的值的任何部分。var()函数不能作为属性名、选择器或者其他除了属性值之外的值。(这样做通常会产生无效的语法或者一个没有关联到变量的值。)
例子:
:root {
--main-bg-color: pink;
}
body {
background-color: var(--main-bg-color);
}
配合上setProperty()接口简单修改css的变量
CSSStyleDeclaration.setProperty() 方法接口为一个声明了CSS样式的对象设置一个新的值 。
语法
style.setProperty(propertyName, value, priority);
参数
propertyName 是一个 DOMString ,代表被更改的CSS属性。
value可选 是一个 DOMString ,含有新的属性值。如果没有指定, 则当作空字符串。
注意: value 不能包含 “!important” --那个应该使用 priority 参数.
priority可选 是一个 DOMString 允许设置 “important” CSS 优先级。如果没有指定, 则当作空字符串。