获取图像宽度高度javascript [英] Get image width height javascript

查看:61
本文介绍了获取图像宽度高度javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好,我有以下代码:

http://jsfiddle.net/hv9gB/3/

    (function() {

    var img = document.getElementById('my_image');

    // Original
    var width, height;

    // Display
    var d_width = img.width;
    var d_height = img.height;

    var updateDetail = function() {
        document
            .getElementById('display_size')
            .innerHTML = 'Display Size: ' + d_width + ' x ' + d_height;

        document
            .getElementById('native_size')
            .innerHTML = 'Original Size: ' + width + ' x ' + height;
    };

    // Using naturalWidth/Height
    if (img.naturalWidth) {
        width = img.naturalWidth;
        height = img.naturalHeight;

        updateDetail();
    } else {
        // Using an Image Object
        img = new Image();
        img.onload = function() {
            width = this.width;
            height = this.height;

            updateDetail();
        };
        img.src = 'http://lorempixel.com/output/nature-q-c-640-480-3.jpg';
    }

}());

那是我的网站:

http://dhems.x10.mx/

但是在我的网站上无法显示图片的宽度和高度

But on my site isn't working show the width and height of image

为什么?!?!

推荐答案

将代码放入

window.onload = function() {
 //insert code here
}

您的js文件在引擎到达图片之前就已执行.您将收到以下控制台错误:

Your js file is executed before the engine reach the picture..You're getting the following console error:

Uncaught TypeError: Cannot read property 'width' of null 

将所有脚本文件放在页面末尾,并将所有css文件放在开头也是一种很好的做法.这将增加页面的加载时间,因为如果JS文件位于开头,则在下载这些文件之前,您的浏览器将不会开始渲染.

It's also a good practice to put all scripts files in the end of the page and all css files in the begin. It will increase the loading time of your page, because if JS files are in the begin, your browser won't start to render until these files are downloaded.

您的代码应如下所示:

window.onload = function() {

var img = document.getElementById('my_image');

// Original
var width, height;

// Display
var d_width = img.width;
var d_height = img.height;

var updateDetail = function() {
    document
        .getElementById('display_size')
        .innerHTML = 'Display Size: ' + d_width + ' x ' + d_height;

    document
        .getElementById('native_size')
        .innerHTML = 'Original Size: ' + width + ' x ' + height;
};

// Using naturalWidth/Height
if (img.naturalWidth) {
    width = img.naturalWidth;
    height = img.naturalHeight;

    updateDetail();
} else {
    // Using an Image Object
    img = new Image();
    img.onload = function() {
        width = this.width;
        height = this.height;

        updateDetail();
    };
    img.src = 'http://lorempixel.com/output/nature-q-c-640-480-3.jpg';
}

}

这篇关于获取图像宽度高度javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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