在Javascript中设置样式属性通过Array创建错误

时间:2014-11-16 20:31:15

标签: javascript html5 dom html5-video undefined

以下代码中出现错误:

var attribute=["position","top","bottom","left","right","zIndex"],
            prop=["fixed","0","0","0","0","-2"];

        for(var i=0;i<attribute.length;i++)
            video.style.attribute[i]=prop[i];

控制台显示错误:Uncaught TypeError: Cannot set property '0' of undefined

请帮助!

2 个答案:

答案 0 :(得分:0)

video.style.attribute尝试读取一个名为attribute的属性,该属性不存在,因此attribute[0]会抛出观察到的错误。

要设置video.style.position = "fixed",您需要在循环中使用[]表示法:

video.style[attribute[i]] = prop[i];

即。 video.style["position"] = "fixed"

答案 1 :(得分:0)

这是一种组织属性和属性的坏方法,实际上是关系的基础:

var attribute=["position","top","bottom","left","right","zIndex"],
            prop=["fixed","0","0","0","0","-2"];

维护和扩展非常困难。您应该关键和值:

var data = {
     "position" : "fixed"
    ,"top" : "0"
    ,"bottom" : "0"
    ,"left" : "0"
    ,"right" : "0"
    ,"zIndex" : "-2"
}

然后,您应该能够使用1行代码设置属性:

for(key in data) video.style[key] = data[key];

完整示例:

var data = {
     "position" : "fixed"
    ,"top" : "0"
    ,"bottom" : "0"
    ,"left" : "0"
    ,"right" : "0"
    ,"zIndex" : "-2"
}
for(key in data) video.style[key] = data[key];