在我的网页上,我有元素(div,sub,按钮等)。它的位置是相对于它们所处的和彼此的div而产生的。这样做的结果是,当使用window.getComputedStyle,时,顶部和左侧属性不是数字值,而宽度和高度是px中的“自动”。
问题是我需要绝对值来测量,所以我想知道是否有办法得到它们。我本来希望window.getComputedStyle能做到的,但很明显,事实并非如此。
下面是一个示例,没有任何格式设置,但存在相同的问题。
如果有jQuery解决方案,我当然也会很感激。
致以亲切的问候,
jaySon
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function test() {
var style = window.getComputedStyle(document.getElementsByTagName("button")[0]);
alert(
"top = " + style.top + //auto
"\nleft = " + style.left + //auto
"\nwidth = " + style.width + //63px
"\nheight = " + style.height //24px
);
}
</script>
</head>
<body>
<div>
<button id="buttonTest" onClick="test()">Test it!</button>
</div>
</body>
</html>
发布于 2014-11-17 17:48:29
getComputedStyle方法返回CSS属性的解析值。
如果样式表作者(You)没有为某些CSS属性(即:顶部、右侧、底部和左侧)指定值,则返回的已解析值将是默认值。这些CSS属性的默认值都是"auto“。
如果您不能或不希望自己在样式表中指定一个值,并且只需要相对于视图左上角的坐标,请考虑使用Element.getBoundingClientRect()。
<html>
<head>
<title>Test</title>
<style>
/* Remove default styling to ensure a top and left value of 0 */
body {margin:0; padding:0}
button {display:block}
</style>
<script type="text/javascript">
function test() {
var button = document.getElementsByTagName("button")[0],
style = window.getComputedStyle(button),
coordinates = button.getBoundingClientRect();
alert (
"top = " + coordinates.top +
"\nleft = " + coordinates.left +
"\nwidth = " + style.width + //63px
"\nheight = " + style.height //24px
);
}
</script>
</head>
<body>
<button id="buttonTest" onClick="test()" >Test it!</button>
</body>
</html>
发布于 2014-11-16 10:13:28
当元素将计算出的top
和left
设置为static
(这是默认的)时,就没有什么可计算的了。在这种情况下,top
和left
是无关的。
https://stackoverflow.com/questions/26955772
复制相似问题