JavaScript gets the real size code instance of the image

  • 2020-03-30 03:59:34
  • OfStack

Pictures on web pages seem to be the same size. We most commonly see the article page with multiple pictures, the size of the picture is usually the same as the width of the page, so that the page is a straight cylindrical shape, the layout will feel very monotonous. I think that's largely because of the limitations of older browsers. But with the popularity of modern browsers (firefox/Google/IE11), browsers have fewer and fewer restrictions on page design, and the imagination of Web programmers can be greatly used.

For example, cold knowledge: do you know how [x] comes from every window? In this article, many pictures exceed the limits of the text width, giving people a sense of jagged and scattered, at the same time, let the big picture in its real size, giving people a more shocking feeling.

But technically, we can easily limit images to the maximum width of the text, keeping them all the same width, instead of the width of the text, we need the size of each image. We can declare the original size of the image when editing on the server. A more flexible way is to dynamically obtain the original size of the image by putting a section of js on the page and dynamically change the size of the image. This is compatible with the old method of maximizing the width of the text, and can render the image to its original size when needed.

How do I use JavaScript to get the original size of an image on the browser side?

var img = $( " #img_id " ); // Get my img elem
var pic_real_width, pic_real_height;
$( " <img/> " ) // Make in memory copy of image to avoid css issues
.attr( " src " , $(img).attr( " src " ))
.load(function() {
pic_real_width = this.width;   // Note: $(this).width() will not
pic_real_height = this.height; // work for in memory images.

The Webkit browser (Google browser, etc.) gets the height and width values after the loaded event of the image. Therefore, you can't use the timeout function to delay, the best way is to use the onload event of the image.

To avoid CSS effects on image size, the code above copies the image into memory for calculation.

If your page is an old page, you can embed this code at the bottom of the page as needed. It doesn't require you to change the old page.

Related articles: