简体   繁体   中英

Unable to get the current margin-left?

In my simple code, I am trying to get the marginLeft of a certain image, but it alerts "undefined" instead of 300, which it should alert (the margin-left is 300 in the css)

Here is my code, thanks

var Left = document.getElementById("Shot").style.marginLeft;
var ParsedLeft = parseInt(Left)
alert(ParsedLeft)

Getting the style the way you're trying only works for inline CSS. For CSS set via a stylesheet, use getComputedStyle :

var Left = window.getComputedStyle(document.getElementById("Shot"));
console.log(Left.marginLeft)

jsFiddle example

If you want just the number without "px" or "em" you could do this:

var el = document.getElementById('Shot');
var style = window.getComputedStyle(el);
var left = style.getPropertyValue('margin-left');
left = left.substring(0, left.length - 2);
console.log(left);

The way you were trying to do it is for inline CSS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM