On my webpage, I've got elements (divs, sub divs, buttons etc.) whose position is generated relative to the div they're in and to each other. This has the result that when using window.getComputedStyle, the top and left property are no number values, but simply "auto" while width and height are in px.
The problem that I need the absolute values for measuring purposes so I was wondering if there's a way to get them somehow. I was hoping window.getComputedStyle would do, but obviously it doesn't.
There's an example below, without any formatting but the same problem.
If there's a jQuery solution, I'd of course appreciate it as well.
Kind regards,
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>
The Window. getComputedStyle() method returns an object containing the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain.
The computed style is the style used on the element after all styling sources have been applied. Style sources: external and internal style sheets, inherited styles, and browser default styles.
The getComputedStyle method returns the resolved value of CSS properties.
If the style sheet author(you) did not specify values for certain CSS properties(ie: top, right, bottom, and left) then the resolved value returned will be the default value. These CSS properties all have a default value of "auto".
If you cannot or don't want to specify a value yourself in the stylesheet and you only need coordinates relative to the top-left of the viewport, consider using 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With