javascript 按类名更改 div 的 style.width
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22054979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change style.width of a div by class name
提问by Omar Gonzalez
I've been trying to change the width of a div with a set.interval animation. It works perfectly fine with getELementByID, but it won't work with getElementsByClassName.
我一直在尝试使用 set.interval 动画更改 div 的宽度。它与 getELEmentByID 一起工作得很好,但它不能与 getElementsByClassName 一起工作。
The code is the following:
代码如下:
var loadingBar = 200;
function animationBarOne(){
document.getElementsByClassName("loading-bar").style.width=(loadingBar+"px");
loadingBar++;
if(loadingBar === 900){
clearInterval(intervalId);
}
}
var intervalId = setInterval(animationBarOne,1);
I'm getting "can't set property width of undefined". As I said it works perfectly with ID, but giving I have like 10 bars to animate I rather use class name so its cleaner.
我收到“无法设置未定义的属性宽度”。正如我所说,它与 ID 完美配合,但给我大约 10 个条形动画我宁愿使用类名,这样它就更干净了。
Thanks in advance.
提前致谢。
回答by Bic
document.getElementsByClassName()
returns an array of elements. You need to loop through the array to modify each one in the list:
document.getElementsByClassName()
返回一个元素数组。您需要遍历数组以修改列表中的每一个:
var loadingBar = 200;
function animationBarOne(){
var elements = document.getElementsByClassName("loading-bar");
for (var i = 0; i < elements.length; i++) {
elements[i].style.width=(loadingBar+"px");
}
loadingBar++;
if(loadingBar === 900){
clearInterval(intervalId);
}
}
var intervalId = setInterval(animationBarOne,1);