Home > Web Front-end > JS Tutorial > How Can I Get an Image's Width and Height Using JavaScript or jQuery?

How Can I Get an Image's Width and Height Using JavaScript or jQuery?

DDD
Release: 2024-12-27 00:03:14
Original
758 people have browsed it

How Can I Get an Image's Width and Height Using JavaScript or jQuery?

Getting Image Dimensions with JavaScript

Question:

Is it possible to programmatically retrieve the dimensions (width and height) of an image on a webpage using JavaScript or jQuery?

Answer:

Yes, you can obtain the dimensions of an image on a webpage using JavaScript or jQuery. Here's how:

JavaScript:

const img = new Image();
img.onload = function() {
  alert(this.width + 'x' + this.height);
}
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';
Copy after login

This code creates a new image object and assigns a load event listener to it. When the image finishes loading, the event listener is triggered and it calculates and alerts the image's width and height. Replace the provided image URL with the actual image you want to check.

jQuery:

jQuery offers a built-in function for retrieving image dimensions:

const imgHeight = $('img').height();
const imgWidth = $('img').width();
Copy after login

Simply replace the '$('img')' selector with the appropriate selector for your image element.

The above is the detailed content of How Can I Get an Image's Width and Height Using JavaScript or jQuery?. For more information, please follow other related articles on the PHP Chinese website!

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