js 获取 image 原始高度

发布时间 2023-05-30 16:33:02作者: 正义的伙伴!
  1. 新版浏览器
// 这个 api 仅支持新版本浏览器, 旧版还是得创建一个内部图片
      setTimeout(() => {
        let imgRef = this.$refs.img
        this.imgWidth = imgRef.naturalWidth
        this.imgHeight = imgRef.naturalHeight
      }, 10)
  1. 旧版浏览器(兼容)

function getImgNaturalDimensions(img, callback) {
    var nWidth, nHeight
    if (img.naturalWidth) { // 现代浏览器
        nWidth = img.naturalWidth
        nHeight = img.naturalHeight
    } else { // IE6/7/8
        var imgae = new Image()
        image.src = img.src
        image.onload = function () {
            callback(image.width, image.height)
        }
    }
    return [nWidth, nHeight]
}