开发者

How do I get the dimensions of an image whose src is dynamically filled by jQuery?

开发者 https://www.devze.com 2023-02-08 07:44 出处:网络
Suppose I have an empty placeholder <img> tag that I want to populate dynamically. I call $(\"img\").attr(\"src\", \"somephoto.jpg\") to point the element to the correct image. However, then I w

Suppose I have an empty placeholder <img> tag that I want to populate dynamically. I call $("img").attr("src", "somephoto.jpg") to point the element to the correct image. However, then I want to do something based on this image's width, but both $开发者_如何学Python("img").width() and $("img").attr("width") return 0.

How can I get the width of the image---or better yet, is there a way to dynamically set the src of an image that is better practice and would solve my problem?


I would personally append the entire new image rather than using an empty img tag's src attribute.

How are they returning zero? Remember that these two methods will return a string representation of the width, ie "10px", and not the integer 10.


You have to wait for the image to load first.

$("img")
  .attr("src", "somephoto.jpg")
  .on("load", function () {
    alert(this.height()+" "+this.width())
  })

My jQuery might be a bit rusty. Here it is in plain ol' JS

var i = new Image()
i.src = "somephoto.jpg"
i.onload = function () {
  alert(this.height + " " + this.width)
}
0

精彩评论

暂无评论...
验证码 换一张
取 消