Home > Web Front-end > JS Tutorial > body text

Javascript Determine Image Size Example Analysis_javascript Skills

WBOY
Release: 2016-05-16 16:44:19
Original
1073 people have browsed it

Usually we judge the size of js images by using the images object, and then using attr to get the image address and then judging . Let’s take a look at some examples.
Easiest way:

Copy code The code is as follows:

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

In the above example, if the page has not been loaded, js will not be able to obtain the image size. For this, we can first determine whether the loading is complete and then determine the image size.

Copy code The code is as follows:



Or use jquery:

Copy code The code is as follows:

$("#imageId").load(function( ){
alert("Loading completed!");
});

Now we can optimize the code

Copy code The code 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 picture address. This is required.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template