Javascript determines the size of the image for example analysis

  • 2020-03-30 03:20:08
  • OfStack

Usually, we judge the size of js images to be Use the images object, and then use attr to get the image address That's it. Let's look at some examples.
The easiest way:


var img=new Image();
    img.src=$('#tlogo').attr('src');
    if(img.width > '240'){
        $('#tlogo').attr('width','240');
}

In the above example, if the page is not fully loaded, then js will not be able to get the size of the image. In this case, we can judge whether the loading is completed before determining the size of the image.


<img id="img2" src="images/1.jpg" />
<script language="JavaScript">
    document.getElementById("img2").onload = function () {
        alert(" Image loading is complete ");
    }
</script>

Or jquery:


$("#imageId").load(function(){
   alert(" Load complete! ");
});

At this point we are ready to optimize the code


$("#tlogo").load(function(){
 var img=new Image();
        img.src=$('#tlogo').attr('src');
        if(img.width > '240'){
        $('#tlogo').attr('width','240');
}
});

Note here :#tlogo is an ID that you add to the image address. This is required.


Related articles: