我指定了ID为testBox的div:
<div id="testBox"></div>并把它写在头部分:
#testBox {
background: red;
width: 25px;
height: 25px;
left: 0;
top: 0;
}然后在身体的底部,我把JS:
var box = document.getElementById("testBox");
console.log(box.style.left);
console.log(box.style.width);使用FireBug in FireFox,但它只是告诉我:
是一根空绳子..。
但是,当我将样式信息放在div标签中时,如下所示:
<div id="testBox" style="background: red;width: 25px;height: 25px;"></div>然后JS就可以完成它的工作,检索我想要的所有信息。
所以,这是获得风格信息的唯一途径吗?所有这些都是内联的,还是我错过了什么,毕竟我对JS和DOM还不熟悉.
发布于 2011-12-27 06:01:10
当您说box.id时,返回给您的是html中声明的box元素的id属性。
当您说box.style时,您正在访问也是基于标记创建的javascript对象。
在创建样式属性的dom-表示时,不使用未内联定义的样式属性。
下面是一个文章,它突出了这种行为。
但是,如果您使用像jQuery这样的库,您可以这样做
$(function(){alert($("#textBox").css("width"));});这会给你你的css值。
更新:
感谢AVD为我指明了正确的方向:这里有一个方法使用他的解决方案,但添加了对IE <9的支持:
var box = document.getElementById("testBox");
var style = window.getComputedStyle ? window.getComputedStyle(box) : box.currentStyle;
alert("Height : " + style["height"]);
alert("Width : " + style["width"]);
alert("Left : " + style["left"]);这是一个小提琴。
发布于 2011-12-27 06:16:48
你可以试试getComputedStyle()。它给出了元素的所有CSS属性的最终使用值。
var box = document.getElementById("testBox");
var style=window.getComputedStyle(box);
console.log("Height : " + style["height"]);
console.log("Width : " + style["width"]);
console.log("Left : " + style["left"]);https://stackoverflow.com/questions/8641572
复制相似问题