gpt4 book ai didi

javascript - 操作 DOM 子项的有效方法

转载 作者:太空宇宙 更新时间:2023-11-04 09:36:03 25 4
gpt4 key购买 nike

我的目标是使用 CSS 在某些文本上获得随机发光效果 animation .我已经有一个工作代码,只是想知道是否有更有效/更简单的解决方案。

HTML:

<span class="foo">
<span class="bar">
</span>
</span>

CSS:

@keyframes masked-animation {
0% {background-position: -1000px 0}
50% {background-position: 1000px 0}
100% {background-position: 1000px 0}
}

.foo{
text-align: center;
font-size: 40px;
font-weight: bold;
display: block;
color: red;
position: absolute;
}

.bar{
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
color: rgba(0,0,0,0);
background-image: linear-gradient(-45deg, rgba(255,255,255,0) 0%, rgba(255,255,255,0.67) 48%, rgba(255,255,255,0.9) 50%, rgba(255,255,255,0.67) 52%, rgba(255,255,255,0) 100%);
background-repeat: no-repeat;
-webkit-background-clip: text;
animation-name: masked-animation;
animation-timing-function: ease-in-out;
animation-iteration-count: infinite;
background-size: 400% 100%;
}

JS:

$('.foo')[0].childNodes[0].nodeValue = "Text";
$('.foo > .bar').css({
"animation-duration" : 8 + Math.round(Math.random()*40)/10 + "s",
"animation-delay" : Math.round(Math.random()*100)/10 + "s"
}).text("Text");

为了使动画看起来正确,它需要位于元素/文本之上。将它放在同一个元素上会使它落后。我尝试使用 ::before但我无法用 JS 选择它,因为它实际上并不存在于 DOM 中。

这需要应用于 <span> 内的多个元素和文本经常更改。

JSFiddle

最佳答案

另一种方法是在 javascript 中创建并直接操作样式表。通过这种方式,元素的迭代由浏览器处理,而不是在 javascript 中处理。

设置这样的样式表在 MDN 的 CSSStyleSheet.insertRule() 中有所描述。示例。

还有一个jQuery library对于这些操作。

还有一个 working example :

var styleElement = document.createElement('style');
document.head.appendChild(styleElement);

var styleSheet = styleElement.sheet,
ruleIdx = styleSheet.insertRule('.target{}',styleSheet.cssRules.length),
rule = styleSheet.cssRules[ruleIdx],
colorize = function() {
var color = Math.random() * 360;
rule.style.color = 'hsl('+color+',100%,50%)';
},
interval = setInterval(colorize,1000);
colorize();
<div class="target" style="font-size:5em;font-weight:bold;font-family:sans-serif">TEST</div>

关于javascript - 操作 DOM 子项的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40321658/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com