Usually we judge JS image size is the use of images objects, and then use attr to get the image address to judge on it, below to see some examples.
The simplest way:
Copy Code code as follows:
var img=new Image ();
img.src=$ (' #tlogo '). attr (' src ');
if (Img.width > ' 240 ') {
$ (' #tlogo '). attr (' width ', ' 240 ');
}
The above example encountered if the page does not finish loading time, then JS can not get the picture size, for which we may first judge whether the load completed before judging the size of the picture.
Copy Code code as follows:
<script language= "JavaScript" >
document.getElementById ("Img2"). onload = function () {
Alert ("Picture loading completed");
}
</script>
or use jquery:
Copy Code code as follows:
$ ("#imageId"). Load (function () {
Alert ("Load complete!") ");
});
So we can optimize the code.
Copy Code code 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.