繁体   English   中英

如何使用DOM检索style.top,还有其他方法吗?

[英]how to retrieve the the style.top with DOM,is there any other way?

我指定了一个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);

在FireFox中使用FireBug,但它只是告诉我:

这是一个空字符串。

但是,当我将样式信息放入div标签中时,如下所示:

<div id="testBox" style="background: red;width: 25px;height: 25px;"></div>

然后JS可以完成工作,检索我想要的所有信息

所以这是唯一获取样式信息的唯一方法吗,否则我只是错过了一些东西,毕竟我对JS和DOM还是陌生的。

您可以尝试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"]);

当您说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"]);

这是一个小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM