gpt4 book ai didi

javascript - 如何在 Javascript 中设置 CSS 关键帧?

转载 作者:行者123 更新时间:2023-12-04 14:21:51 24 4
gpt4 key购买 nike

我有一个如下所示的 CSS 关键帧,我的问题是我想将其设置为 JavaScript(放在我的 div 中已经有一些功能),以便我可以将“元素”值返回给我的函数

.cylon-eye {
background-color: yellow;
background-image: linear-gradient( to right, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.1) 50%, rgba(255, 255, 255, 0.9) 75%);
color: none;
height: 100%;
width: 20%;
animation: 4s linear 0s infinite alternate move-eye;
}
@keyframes move-eye {
from {
margin-left: -20%;
}
to {
margin-left: 100%;
}
}


我在建议后尝试转换如下,我应该调用的返回值是 var cylon-eye = document.getElementById("cylon-eye"); ?
<script type="text/javascript">
function appendStyle(styles) {
var css = document.createElement('style');
css.type = 'text/css';

if (css.styleSheet) css.styleSheet.cssText = styles;
else css.appendChild(document.createTextNode(styles));

document.getElementsByTagName("head")[0].appendChild(css);

}

var styles = '#cylon-eye { background-color: yellow; background-image: linear-gradient(to right,rgba(255,255,255, 0.9) 25%,rgba(255,255,255, 0.1) 50%,rgba(255,255,255, 0.9) 75%); color: none; height: 100%; width: 20%;animation: 4s linear 0s infinite alternate move-eye; z-index: 10;}';
var keyFrames = '\
@keyframes move-eye {\
from {\
margin-left: -20%;\
}\

to {\
margin-left: 100%;\
}\
}';

window.onload = function() { appendStyle(styles) };
</script>

最佳答案

给大家分享两个片段,一个是使用 CSS + javascript 另一个只使用 javascript ,你可以使用任何你喜欢的东西。希望它对你有帮助。

WITH JAVASCRIPT



let dynamicStyles = null;

function addAnimation(body) {
if (!dynamicStyles) {
dynamicStyles = document.createElement('style');
dynamicStyles.type = 'text/css';
document.head.appendChild(dynamicStyles);
}

dynamicStyles.sheet.insertRule(body, dynamicStyles.length);
}

addAnimation(`
@keyframes move-eye {
from {
margin-left: -20%;
}
to {
margin-left: 100%;
}
}
`);



var element = document.createElement("div");
element.className = "cylon-eye";
element.style.height = "50px";
element.style.width = "50px";
element.style.backgroundImage = "linear-gradient(to right,rgba(255, 0, 0, 0.1) 25%,rgba(255, 0, 0) 50%,rgba(255, 0, 0, 0.1) 75%)";
element.style.animation = "4s linear 0s infinite alternate move-eye";

document.body.appendChild(element);


WITH CSS + JAVASCRIPT



var element = document.createElement("div");
element.className = "cylon-eye";
element.style.height = "50px";
element.style.width = "50px";
document.body.appendChild(element);
.cylon-eye {
background-color: yellow;
background-image: linear-gradient(to right, rgba(255, 0, 0, 0.9) 25%, rgba(255, 0, 0, 0.1) 50%, rgba(255, 0, 0, 0.9) 75%);
color: none;
height: 100%;
width: 20%;
animation: 4s linear 0s infinite alternate move-eye;
}

@keyframes move-eye {
from {
margin-left: -20%;
}
to {
margin-left: 100%;
}
}

关于javascript - 如何在 Javascript 中设置 CSS 关键帧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59573722/

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