获取图像宽度高度javascript

use*_*036 3 javascript height image width

好吧,我有这个代码:

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';
    }

}());
Run Code Online (Sandbox Code Playgroud)

那是我的网站:

http://dhems.x10.mx/

但在我的网站上工作不显示图像的宽度和高度

为什么?!?!

Dee*_*psy 5

把你的代码放进去

window.onload = function() {
 //insert code here
}
Run Code Online (Sandbox Code Playgroud)

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

Uncaught TypeError: Cannot read property 'width' of null 
Run Code Online (Sandbox Code Playgroud)

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

您的代码应如下所示:

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';
}

}
Run Code Online (Sandbox Code Playgroud)