1

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";返回“未捕获的类型错误:无法设置未定义的属性‘左’”。但是,modalChildren[x].className两者modalChildren[x].offsetWidth;都返回预期值,所以我不确定为什么我可以在这里查看但不能更新 css。

4

2 回答 2

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

于 2012-12-15T06:35:51.387 回答
1

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

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

您可以通过键入来查看此列表

console.log(modalChildren) 

由于 textNode 没有样式属性,因此会引发错误

于 2012-12-15T06:36:23.463 回答