简体   繁体   中英

How to get style.left

Does anyone know, I have a div element when the first load I set its attributes to right:0 and bottom:0 ; I want to get its style.left but it return NaN . So how to get it or is there another way?

<div id="myDiv">Sample</div>
<script type="text/javascript">
    var setMe = document.getElementById("myDiv");
    setMe.setAttribute("style", "background-color: red;
        position: absolute;
        width: 670px;
        height: 370px;
        right: 0;
        bottom: 0;");
    alert(setMe.style.left)
</script>

Try it using getComputedStyle() : ( Demo )

var setMe=document.getElementById("myDiv");

setMe.setAttribute("style", "background-color:red;position:absolute;width:670px;height:370px;right:0;bottom:0;");

alert(window.getComputedStyle(setMe).left);

Use offsetLeft attribute.

<html>
<head></head>
<body>
<div id="myDiv">Sample</div>
<script type="text/javascript">
    var setMe=document.getElementById("myDiv");
    setMe.setAttribute("style", "background-color:red;position:absolute;width:670px;height:370px;right:0;bottom:0;");
    alert(setMe.offsetLeft);
</script>
</body>
</html>

you have three options:

style property // --> Returns an object that represents the element's style attribute (setted when parsed)

getAttribute // --> returns the value of the named attribute on the specified element.

computedStyle // -->  gives the final used values of all the CSS properties of an element.

Take a look at this fiddle (demo) for an example in every one.

Also:

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