Javascript可以访问原生图像大小吗? [英] Can Javascript access native image size?

查看:135
本文介绍了Javascript可以访问原生图像大小吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个jQuery函数,我想要访问图像的原始大小以及页面上为其指定的大小。我想为每个设置一个变量。

I'm writing a jQuery function where I'd like to access both the native size of an image, and the size specified for it on the page. I'd like to set a variable for each.

这是怎么做的?

推荐答案

现代浏览器



当我在2009年写下这个答案时,浏览器的格局就大不相同了。现在任何合理的现代浏览器都支持 Pim Jager的建议,使用 img.naturalWidth img.naturalHeight 。看看他的答案。

Modern browsers

When I wrote this answer back in 2009 the browser landscape was much different. Nowadays any reasonably modern browser supports Pim Jager's suggestion using img.naturalWidth and img.naturalHeight. Have a look at his answer.

// find the element
var img = $('#imageid');

/* 
 * create an offscreen image that isn't scaled
 * but contains the same image.
 * Because it's cached it should be instantly here.
 */

var theImage = new Image();
theImage.src = img.attr("src");

// you should check here if the image has finished loading
// this can be done with theImage.complete

alert("Width: " + theImage.width);
alert("Height: " + theImage.height);

这篇关于Javascript可以访问原生图像大小吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆