2015-04-23 88 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得到这个。