我目前正在做一个基本的拖放系统,需要检索被移动的元素的top
和left
属性。如果我这样做:JavaScript检索元素的CSS值
var mover = document.getElementById('mover');
alert(mover.style.top);
会提醒没有(“”)
有,而不必与JS先来定义它们检索CSS值(JS)的方法吗?
我目前正在做一个基本的拖放系统,需要检索被移动的元素的top
和left
属性。如果我这样做:JavaScript检索元素的CSS值
var mover = document.getElementById('mover');
alert(mover.style.top);
会提醒没有(“”)
有,而不必与JS先来定义它们检索CSS值(JS)的方法吗?
你需要,如果你想检索计算,而不是定义属性的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>
var mover = document.getElementById('mover');
alert(mover.offsetTop);
alert(mover.offsetLeft);
他想要检索CSS值 - 不能从其他值推断出它们 –
这不回答问题 – Cristik
你可以得到元素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>
有三种可能top
s到担心:
实际的顶部位置。每个元素都有页面布局产生的顶部,无论它是否具有top
属性的计算值。通过getBoundingClientRect
获取此内容。
CSS属性的计算值top
。如getComputedStyle
得到这个,正如在其他答案中提到的
元素上设置的当前样式值为top
。像你试图的那样用elt.style.top
得到这个。
https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle – dfsq
看到http://stackoverflow.com/questions/6338217/get-a-css-value -with-javascript –
很酷!我会试试看。这很快! – Tobsta