JavaScript judge picture size size case Analysis _javascript Tips

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.