2015-04-23 92 views
0

我目前正在做一個基本的拖放系統,需要檢索被移動的元素的topleft屬性。如果我這樣做:JavaScript檢索元素的CSS值

var mover = document.getElementById('mover'); 
alert(mover.style.top); 

會提醒沒有(「」)

有,而不必與JS先來定義它們檢索CSS值(JS)的方法嗎?

+0

https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle – dfsq

+1

看到http://stackoverflow.com/questions/6338217/get-a-css-value -with-javascript –

+0

很酷!我會試試看。這很快! – Tobsta

回答

2

你需要,如果你想檢索計算,而不是定義屬性的getComputedStyle使用。

https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

從MDN鏈接...

<script> 
    function getTheStyle(){ 
    var elem = document.getElementById("elem-container"); 
    var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("height"); 
    document.getElementById("output").innerHTML = theCSSprop; 
    } 
    getTheStyle(); 
</script> 
-1
var mover = document.getElementById('mover'); 
alert(mover.offsetTop); 
alert(mover.offsetLeft); 
+0

他想要檢索CSS值 - 不能從其他值推斷出它們 –

+0

這不回答問題 – Cristik

0

你可以得到元素position().top的位置,可以檢索到的CSS值.css("margin-top").css("top")

alert($('#mover').position().top); 
 
alert($('#mover').css("margin-top"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div id='mover'>dasdasD</div>


既然你不喜歡的jQuery,這裏是在純JS的解決方案

更新:

var mover = document.getElementById('mover'); 
 
alert(window.getComputedStyle(mover).getPropertyValue('margin-top'));
<div id='mover'>dasdasD</div>


+0

我不喜歡jQuery,寧可不使用它。 – Tobsta

+0

@Tobsta根據你的需要編輯 – Tushar

+0

我非常懷疑你的'margin-top'方法會起作用。 – 2015-04-23 08:10:58

0

有三種可能top s到擔心:

  1. 實際的頂部位置。每個元素都有頁面佈局產生的頂部,無論它是否具有top屬性的計算值。通過getBoundingClientRect獲取此內容。

  2. CSS屬性的計算值top。如getComputedStyle得到這個,正如在其他答案中提到的

  3. 元素上設置的當前樣式值爲top。像你試圖的那樣用elt.style.top得到這個。