是否可以制作删除线动画? CSS / JS
我试图让文本装饰从左到右显示,就像用钢笔划掉一样。
有没有办法在不更改其背后的文本的情况下做到这一点?
提前致谢!
document.querySelector('h1').addEventListener('click', (e) => {
e.target.classList.toggle('strikethrough')
})
.strikethrough {
text-decoration: line-through;
text-decoration-style: wavy;
text-decoration-thickness: 15%;
animation: strike 3s linear;
}
@keyframes strike {
0% {width: 0;}
100% {width: 100%;}
}
<h1>CROSS ME OUT</h1>
I am trying to get the text decoration to appear from left to right, as if it is being crossed out with a pen.
Is there a way to do this without making changes to the text behind it?
Thanks in advance!
document.querySelector('h1').addEventListener('click', (e) => {
e.target.classList.toggle('strikethrough')
})
.strikethrough {
text-decoration: line-through;
text-decoration-style: wavy;
text-decoration-thickness: 15%;
animation: strike 3s linear;
}
@keyframes strike {
0% {width: 0;}
100% {width: 100%;}
}
<h1>CROSS ME OUT</h1>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您愿意接受使用直线作为删除线(而不是取决于字体本身的删除线样式),那么只需在
元素并使用
transform:translateX(-100%)
将其 100% 向一侧偏移。我们给它一个顶部边框,其宽度取决于字体大小(即使用em
单位),以及一个颜色,其值取决于当前字体颜色(即使用currentColor
)。您可以使用 CSS 过渡设置该行条目的持续时间和缓动功能。添加
.strikethrough
类后,偏移量将简单地设置为transform: translateX(0)
。需要注意的是,这个技巧仅适用于不间断的行。如果你的 h1 元素将跨多行渲染,那么它就不起作用。
请参阅下面的概念验证示例:
If you are willing to accept using a straight line as the strike through (instead of depending on the font's own strikethrough styles), then it is just a matter of overlaying a div on top of the
<h1>
element and offsetting it 100% to the side usingtransform: translateX(-100%)
. We give it a top border whose width is font-size dependent (i.e. useem
units), and a color whose value is dependent on the current font color (i.e. usecurrentColor
).You can use CSS transitions set the duration and easing function of the entry of this line. When the
.strikethrough
class is added, the offset is simply set totransform: translateX(0)
.A caveat is that this trick only works for non-breaking lines. If your h1 element will render across multiple lines, then it wouldn’t work.
See proof-of-concept example below: