简体   繁体   中英

Javascript. Can't get element style

I'm trying to get width & height of the img element. It gives 0px whatever I do.

function foo(element){
if(element){
    var el=document.querySelector(element);
    var img=el.getElementsByTagName("img")[0];
    alert(img.style.width);
}
}
foo();

And the html:

<div id="theid" class="theclass">
   <img id="img" alt="img" name="the img" src="img/img.jpg" />
</div>

<script>
foo("#theid");
</script>

I've also tried .offsetWidth , .clientWidth and defaultView.getComputedStyle(img,"");

How about this

function foo(imgId){
    var img=document.getElementById(imgId);
    alert(img.offsetWidth);
}

foo('img');
<div id="theid" class="theclass">
   <img id="img" alt="img" name="the img" src="img/img.jpg" />
</div>

<script>
    foo("#theimg");
</script>

You are calling foo() by passing #theimg which is not present in document, call by passing #img , ie like this

<script>
    foo("#img");
</script>

if you use above img id, remove var img=el.getElementsByTagName("img")[0]; in your function, we can directly access it.Okay

<script>
    foo("#theid");
</script>

use this to keep your function as it is. Okay

It'll give 0px, if the image failed to load otherwise it'll give the width and height of the actual image, And if you want to access the attributes like left, right, top, bottom for these attributes we need to set image position to absolute then we can access.

Use .naturalWidth & .naturalHeight to get the actual size of image

     function foo(element){
if(element){
    var el=document.querySelector(element);
    var img=el.getElementsByTagName("img")[0];
    alert(img.naturalWidth );
}
}
foo("#theid");

DEMO

Image height/width is always returned 0px unless defined in CSS.

Try this piece of code, but you are loading the image again in this case (could be cached, but still).

var image = new Image();

// replace with appropriate library method
image.addEventListener("load", function() {
    //get image height/width here
}, false);

image.src = el.getElementsByTagName("img")[0].src;

You need to use the element offsetWidth

Here is a working fiddle and the code:

function foo(element) {
    if (element) {
        var el = document.getElementById(element);
        alert(el.offsetWidth);
    }
}
foo("theid");

Note that I have used the document.getElementById only as that will get the element. No need to have getElementsByTagName in this case. And do not prefix the id with a '#' as that notation is of jquery not javascript.

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