【发布时间】:2019-12-06 02:24:37
【问题描述】:
这里有一个简单的代码来动画和绘制一条简单的线。
线的长度或宽度在这里定义:
@-webkit-keyframes navShow {
from { opacity: 1; width: 0vw; }
to { opacity: 0.5; width: 29vw;} /* Final length would be 29vw */
}
问题是我想知道如果我们想通过 javascript 定义行的长度怎么办!
如何将javascript长度变量传递给CSS并更改width: 29vw;
注意:CSS 动画应该是完整的,我需要像 vw 这样的视口单位...
let navBar = document.getElementById("navBar");
navBar.classList.add("navBarShow");
// search the CSSOM for a specific -webkit-keyframe rule
function findKeyframesRule(rule)
{
// gather all stylesheets into an array
var ss = document.styleSheets;
// loop through the stylesheets
for (var i = 0; i < ss.length; ++i) {
// loop through all the rules
for (var j = 0; j < ss[i].cssRules.length; ++j) {
// find the -webkit-keyframe rule whose name matches our passed over parameter and return that rule
if (ss[i].cssRules[j].type == window.CSSRule.WEBKIT_KEYFRAMES_RULE && ss[i].cssRules[j].name == rule)
return ss[i].cssRules[j];
}
}
// rule not found
return null;
}
// remove old keyframes and add new ones
function change(anim)
{
// find our -webkit-keyframe rule
var keyframes = findKeyframesRule(anim);
// remove the existing 0% and 100% rules
keyframes.deleteRule("0%");
keyframes.deleteRule("100%");
// create new 0% and 100% rules
keyframes.appendRule("0% { opacity: 1; width: 0vw; }");
keyframes.appendRule("100% {opacity: 0.5; width: 60vw; }");
// assign the animation to our element (which will cause the animation to run)
navBar.style.webkitAnimationName = anim;
}
// begin the new animation process
function startChange()
{
// remove the old animation from our object
navBar.style.webkitAnimationName = "none";
// call the change method, which will update the keyframe animation
setTimeout(function(){change("navShow");}, 0);
}
startChange();
#navBar {
position: absolute;
width: 0vw;
border-bottom: 1vh solid rgba(204,193,218);
left: 10.2vw;
top: 77vh;
opacity: 0;
}
.navBarShow {
animation: navShow 0.4s cubic-bezier(0.785, 0.135, 0.15, 0.86);
animation-fill-mode: forwards ;
}
@-webkit-keyframes navShow {
0%{ opacity: 1; width: 0vw; }
100%{ opacity: 0.5; width: 29vw;}
}
<div id="navBar"></div>
【问题讨论】:
-
或使用 CSS 自定义属性(CSS 变量) - codepen.io/Paulie-D/pen/wvBaXvo
-
我已经更新了代码但是还是不行...
-
您提供的答案中的代码也不起作用......
-
只是阅读错误消息,您似乎需要在尝试删除它们之前检查 0% 和 100% 规则是否存在。 - 第一次他们不存在。
标签: javascript html css