Javascript - 动态更改元素的宽度

时间:2012-12-15 06:27:30

标签: javascript

Stack上有一些类似的问题,但我认为我的一些语法错误是我的结果。无论如何,我在javascript中构建一个灯箱,并希望动态地将绝对位置(left % css)设置为元素宽度的一半。

这是代码中的一个片段。完整代码在这里http://jsfiddle.net/Yab3Q/4/

var modal = document.getElementById(btnId+"-modal");
var modalChildren = modal.childNodes;

for (var x = 0; x<modalChildren.length; x++){
    if (!(modalChildren[x].className === "lightBox")){
        var childWidth = modalChildren[x].offsetWidth;
        var halfWidth = childWidth / 2;
        modalChildren[x].style.left = halfWidth + "px";
    }
}

modalChildren[x].css.left = halfWidth + "px";正在返回“未捕获的TypeError:无法设置未定义的属性'左'”。但是,modalChildren[x].classNamemodalChildren[x].offsetWidth;都会返回预期值,因此我不确定为什么我可以查看但不会在此处更新css。

2 个答案:

答案 0 :(得分:1)

文本节点没有样式属性: 记录并检查:

for (var x = 0; x<modalChildren.length; x++){
            console.log(modalChildren[x]);
            console.log(modalChildren[x].style);
            if (!(modalChildren[x].className === "lightBox")){
                var childWidth = modalChildren[x].offsetWidth;
                var halfWidth = childWidth / 2;
                modalChildren[x].style.left = halfWidth + "px";
            }
        }

查看节点类型:http://www.javascriptkit.com/domref/nodetype.shtml

答案 1 :(得分:1)

您尝试更改以下元素的样式属性:

0: <div>
1: #text
2: <img>
3: #text

您可以输入

自行查看此列表
console.log(modalChildren) 

由于textNode没有样式属性,因此会抛出错误

相关问题