简体   繁体   English

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

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

i specified a div with a ID of testBox: 我指定了一个ID为testBox的div:

<div id="testBox"></div>

and style it in the head section : 并在头部设置样式:

#testBox {
        background: red;
        width: 25px;
        height: 25px;
        left: 0;
        top: 0;
            }

then at the bottom of the body,i put the JS : 然后在身体底部,我放上JS:

var box = document.getElementById("testBox");
        console.log(box.style.left);
        console.log(box.style.width);

use the FireBug in FireFox ,but it just tell me: 在FireFox中使用FireBug,但它只是告诉我:

it's an empty string.... 这是一个空字符串。

But when i put the style infomation in the div tag like this: 但是,当我将样式信息放入div标签中时,如下所示:

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

then the JS could do its work,retrieve all the information i want 然后JS可以完成工作,检索我想要的所有信息

so is this the only way to get the style information whit it all inline ,or i just miss something,after all i am just new to the JS and DOM .... 所以这是唯一获取样式信息的唯一方法吗,否则我只是错过了一些东西,毕竟我对JS和DOM还是陌生的。

You may try getComputedStyle() . 您可以尝试getComputedStyle() It gives the final used values of all the CSS properties of an element. 它给出了元素所有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"]);

When you say box.id what is returned to you is the id attribute of the box element as declared in your html. 当您说box.id ,返回给您的是html中声明的box元素的id属性。

When you say box.style you are accessing a javascript object also created based on your markup. 当您说box.style您正在访问的也是基于您的标记创建的javascript对象。

Styling attributes that are not defined inline are not used when the dom-representation of the style attribute is created. 创建样式属性的dom表示形式时,不会使用未内联定义的样式属性。

Here is an article which highlights this behaviour. 这是一篇强调此行为的文章

However, if you use a library like jQuery you can do 但是,如果您使用类似jQuery的库,则可以

$(function(){alert($("#textBox").css("width"));});

and this will give you your css value. 这将为您提供CSS价值。

UPDATE: 更新:

Thanks to AVD for pointing me in the right direction: Here is a method which uses his solution but adds support for IE < 9: 感谢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"]);

Here is a fiddle . 这是一个小提琴

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

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