使用JavaScript - 我們可以設置元素的相對位置,如獲取元素位置 - {absolute | relative | fixed}返回空值?
object.style.position="absolute"||"fixed"||"relative"
但是,在使用相同的console.log(object.style.position)
- 它不返回應用的對象上的位置 - 它返回NULL
。我在這裏錯過了什麼,或者有另一種方式來實現我想要實現的?
使用JavaScript - 我們可以設置元素的相對位置,如獲取元素位置 - {absolute | relative | fixed}返回空值?
object.style.position="absolute"||"fixed"||"relative"
但是,在使用相同的console.log(object.style.position)
- 它不返回應用的對象上的位置 - 它返回NULL
。我在這裏錯過了什麼,或者有另一種方式來實現我想要實現的?
.style
代表元素本身的設置,很像style
屬性。您可以改用getComputedStyle
:http://jsfiddle.net/qAbTz/1/。
var div = document.getElementById("div");
console.log(div.style.position); // "" (not null by the way)
console.log(getComputedStyle(div).position); // "fixed"
瀏覽器兼容性?.. [MDN鏈接](https://developer.mozilla.org/en/DOM/window.getComputedStyle#Browser_compatibility)..但是,怪癖提供了一個解決方案..所以,將研究它。 。謝謝.. :) –
@Vivek Chandra:jQuery支持其他瀏覽器以及我相信;你可以看看它的來源,看看如何。似乎它使用'.currentStyle'(如果可用)。 – pimvdb
目前尚未使用jQuery。想自己解決 - 通過[quirks](http://www.quirksmode.org/dom/getstyles.html)尋找這個解決方案..希望它能解決我的問題 –
還要注意(由pimvdb呈現相同的邏輯),如果你指定爲對象的部分款式的初始位置,它是由div.style.position訪問。
<div id="div" style="position: absolute;"></div>
它的工作:http://jsfiddle.net/9TpfT/ – Mageek
@mageek - 不工作(我真正想要的)版本 - [小提琴](http://jsfiddle.net/ 9TpfT/1 /) –
只有在沒有明確設置的情況下它纔會返回null。如果已設置,則會返回該值。 –