簡體   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