Home  >  Article  >  Web Front-end  >  JavaScript code example to get the real size of the picture_javascript skills

JavaScript code example to get the real size of the picture_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:35:451098browse

Image sizes on web pages all seem to be the same. In the article pages we most often see with multiple pictures, the size of the pictures is usually the same as the width of the page. In this way, the page looks like a straight cylinder. If you see this layout too much, it will feel very monotonous. The reason for this situation, I think, is largely due to the limitations of old browsers. However, 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 utilized.

For example, trivia: Do you know where the [x] in every window comes from? In this article, many pictures exceed the limit of text width, giving people a sense of unevenness. At the same time, allowing large pictures to be displayed in their true size gives people a more shocking feeling.

But technically, we can easily limit the images by the maximum width of the text, so that they all maintain the same width. Instead of pressing the width of the text, we need each image to have its own size. We can declare the original size of the image when editing on the server side. A more flexible way is to dynamically obtain the original size of the image by placing a piece of js on the page, and dynamically change the display size of the image. This is not only compatible with the old method of maximizing text width, but also allows images to display their original size when needed.

How to get the original size of the image on the browser side using JavaScript?

Copy code The code is as follows:

var img = $(“#img_id”); // Get my img elem
var pic_real_width, pic_real_height;
$(“”) // 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.
});

Webkit browsers (Google Chrome, etc.) can only obtain the height and width values ​​after the loaded event of the image. Therefore, you cannot use the timeout function to delay waiting. The best way is to use the onload event of the image.

In order to avoid the impact of CSS on the image size, the above code copies the image into memory for calculation.

If your page is an old-fashioned page, you can embed this code at the bottom of the page as needed. It does not require you to modify the original page.

Statement:
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