Home >Web Front-end >JS Tutorial >js method to determine the actual width and height of the image after the image is loaded_javascript skills

js method to determine the actual width and height of the image after the image is loaded_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:13:391324browse

The example in this article describes the method of js to determine the actual width and height of the image after the image is loaded. Share it with everyone for your reference, the details are as follows:

Usually, we will use jq’s .width()/.height() method to get the width/height of the image or use js’s .offsetwidth/.offsetheight method to get the width/height of the image, but these methods are not used when we pass After setting the width and height of the image in the style, what is obtained is not the actual width and height of the image. This is obviously not the result we want sometimes. So is there a way to obtain such actual width and height? The answer is yes. The following code can solve this problem:

<img src="01.jpg" id="test" width="250px">

js code:

//图片加载完成后获取图片实际宽高
var _test = document.getElementById("test");
test.onload = function(){
  imgSize.call(_test);
}
function imgSize(){
  var imgObj = new Image();
  imgObj.src = this.src;
  alert(imgObj.width + "\n" + imgObj.height);
}

If you want to call this actual width and height in other methods, you should change alert(imgObj.width + "n" + imgObj.height); to return imgObj, and then the calling method:

window.onload = function(){
    function a(){
      var real= imgSize.call(_test);
      var realwidth = real.width;
      alert(realwidth);
    }
    a();
}

The above method is too cumbersome. After my own refinement, the abbreviation is as follows:

window.onload = function(){
    var _test = document.getElementById("test"); //若是jq,则直接将此代码换成 var _test = $("#test"); 即可。
    var imgObj = new Image();
    imgObj.src = _test.src; //若是jq,则直接将此代码换成 imgObj.src = _test.attr("src"); 即可。
    alert(imgObj.width);
}

In this way, the actual width and height of the image can be directly called in other methods.

Readers who are interested in more JavaScript-related content can check out the special topics on this site: "Summary of JavaScript search algorithm techniques", "Summary of JavaScript animation special effects and techniques", "Summary of JavaScript errors and debugging techniques", "Summary of JavaScript data structures and algorithm techniques", "Summary of JavaScript traversal algorithms and techniques" and "JavaScript Mathematics Summary of operation usage

I hope this article will be helpful to everyone in JavaScript programming.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn