获取图片原始大小:NaturalWidth and NaturalHeight

本文转自:https://www.w3ctech.com/topic/112

现代浏览器中获取实际宽度和高度

现代浏览器(包括IE9)为IMG元素提供了naturalWidthnaturalHeight属性来获取实际宽度与高度 ,代码如下:

var 
  nWidth = document.getElementById('example').naturalWidth,
  nHeight = document.getElementById('example').naturalHeight;

在IE7,8中获取实际宽度和高度

在IE8及以前浏览器中并不支持naturalWidthnaturalHeight属性。为IE7,8采用new Image()的方式来获取widthheight

  function getNatural (DOMelement) {
    var img = new Image();
    img.src = DOMelement.src;
    return {width: img.width, height: img.height};
  }

  var 
  natural = getNatural(document.getElementById('example')),
  nWidth = natural.width,
  nHeight = natural.height;

jQuery naturalWidth() and naturalHeight()

为jQuery添加了两个方法:naturalWidth()naturalHeight()

(function($){
    var
    props = ['Width', 'Height'],
    prop;

    while (prop = props.pop()) {
    (function (natural, prop) {
      $.fn[natural] = (natural in new Image()) ? 
      function () {
      return this[0][natural];
      } : 
      function () {
      var 
      node = this[0],
      img,
      value;

      if (node.tagName.toLowerCase() === 'img') {
        img = new Image();
        img.src = node.src,
        value = img[prop];
      }
      return value;
      };
    }('natural' + prop, prop.toLowerCase()));
    }
  }(jQuery));

  // 如何使用:
  var 
  nWidth = $('img#example').naturalWidth(),
  nHeight = $('img#example').naturalHeight();
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值