Usually, we can use images object to judge the size of js images, and then use attr to obtain the image address and then make judgments . Let’s see some examples below.
The easiest way:
The code copy is as follows:
var img=new Image();
img.src=$('#tlogo').attr('src');
if(img.width > '240'){
$('#tlogo').attr('width','240');
}
In the example above, if the page has not been loaded, then js cannot get the image size. In this case, we can first determine whether the loading is completed and then judge the image size.
The code copy is as follows:
<img id="img2" src="images/1.jpg" />
<script language="JavaScript">
document.getElementById("img2").onload = function () {
alert("Image loading completed");
}
</script>
Or use jquery:
The code copy is as follows:
$("#imageId").load(function(){
alert("Loading completed!");
});
So far we can optimize the code
The code copy is as follows:
$("#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 added to your image address. This is a must.