JS获取图片的原始宽度和高度

页面中的img元素,想要获取它的原始尺寸,以宽度为例,可能首先想到的是元素的innerWidth属性,或者jQuery中的width()方法。如下:

<img id="img" src="1.jpg">
 
<script type="text/javascript">
    var img = document.getElementById("img");
    console.log(img.innerWidth); // 600
</script>

这样貌似可以拿到图片的尺寸。

但是如果给img元素增加了width属性,比如图片实际宽度是600,设置了width为400。这时候innerWidth为400,而不是600。显然,用innerWidth获取图片原始尺寸是不靠谱的

这是因为 innerWidth属性获取的是元素盒模型的实际渲染的宽度,而不是图片的原始宽度

<img id="img" src="1.jpg" width="400">
 
<script type="text/javascript">
    var img = document.getElementById("img");
    console.log(img.innerWidth); // 400
</script>

jQuery的width()方法在底层调用的是innerWidth属性,所以width()方法获取的宽度也不是图片的原始宽度。

那么该怎么获取img元素的原始宽度呢?

naturalWidth / naturalHeight

现代浏览器(包括IE9)为img元素提供了 naturalWidth 和 naturalHeight属性来获取图片的实际宽度与高度 。如下:

var naturalWidth = document.getElementById('img').naturalWidth,
    naturalHeight = document.getElementById('img').naturalHeight;

​naturalWidth / naturalHeight在各大浏览器中的兼容性如下:

所以,如果不考虑兼容至IE8的,可以放心使用naturalWidth / naturalHeight属性了。

IE7/8中的兼容性实现:

在IE8及以前版本的浏览器并不支持naturalWidth和naturalHeight属性。

在IE7/8中,我们可以采用new Image()的方式来获取图片的原始尺寸,如下:

function getNaturalSize (DomElement) {
    var img = new Image();
    img.src = DomElement.src;
    return {
        width: img.width,
        height: img.height
    };
}
  
// 使用
var natural = getNaturalSize (document.getElementById('img')),
    natureWidth = natural.width,
    natureHeight = natural.height;
  
IE7+浏览器都能兼容的函数封装:
  
function getNaturalSize (DomElement) {
    var natureSize = {};
    if(window.naturalWidth && window.naturalHeight) {
        natureSize.width = DomElement.naturalWidth;
        natureSizeheight = DomElement.naturalHeight;
    } else {
       var img = new Image();
        img.src = DomElement.src;
        natureSize.width = img.width;
        natureSizeheight = img.height;
    }
    return natureSize;
}
  
// 使用
var natural = getNaturalSize (document.getElementById('img')),
    natureWidth = natural.width,
    natureHeight = natural.height;

 

转载于:https://www.cnblogs.com/wangxi01/p/8079498.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值