使用新的Image()获取图像大小会返回0

时间:2015-01-29 06:41:27

标签: javascript

我正在尝试从输入文本路径加载图像并设置其大小以进行预览。

所以我有这个对象来处理设置:

var Settings = {
    // some other variables
    settLogoLeftVisibility: "true",
    settLogoLeftPath: "OS_logo.jpg",
    settLogoRightVisibility: "true",
    settLogoRightPath: "OS_logo.jpg",
    // some more variables
    load: function() {
        // load the settings from localStorage, or load the defaults
        // set the image path and resize it
        var tempLogoLeftWidth;
        var tempLogoLeftHeight;

        function tempLogoGetWH() {
            tempLogoLeftWidth = this.width;
            tempLogoLeftHeight = this.height;
            return true;
        }
        tempLogoLeft = new Image();
        tempLogoLeft.onload = tempLogoGetWH;

        if (localStorage.settLogoLeftPath) {
            tempLogoLeft.src = "../logos/" + localStorage.settLogoLeftPath; 
        }
        else {
            tempLogoLeft.src = "../logos/" + this.settLogoLeftPath;
        } 
        alert(tempLogoLeft.src);
        alert(tempLogoLeftWidth);
        alert(tempLogoLeftHeight);
    }
}

事实是,它会警告正确的路径,但tempLogoLeftWidth和tempLogoLeftHeight都被警告为未定义,因此我无法进一步处理它们并设置我需要的大小。

编辑:我调用了Settings.load();在我的settings.html页面的最后,如下所示:

// some tables, inputs and buttons
<td>Left logo preview<br>
<img class="settingsLogo" id="settingsLogoLeft"></td>
<td><input type="checkbox" id="settLogoLeftVisibility" value="true" onChange="Settings.preview();"> Enable left logo<br>
<input type="text" id="settLogoLeftPath" size="20" onChange="Settings.preview();"> File name (logos/x.yyy)<br>
<script>
Settings.load();
Settings.preview();
</script>
</body>

Chrome JS控制台中没有错误。

有什么想法吗? 非常感谢你的时间!

1 个答案:

答案 0 :(得分:1)

这没关系

&#13;
&#13;
var Settings = {
    // some other variables
    settLogoLeftVisibility: "true",
    settLogoLeftPath: "OS_logo.jpg",
    settLogoRightVisibility: "true",
    settLogoRightPath: "OS_logo.jpg",
    // some more variables
    load: function() {
        // load the settings from localStorage, or load the defaults
        // set the image path and resize it
        var tempLogoLeftWidth;
        var tempLogoLeftHeight;

        function tempLogoGetWH() {
            tempLogoLeftWidth = this.width;
            tempLogoLeftHeight = this.height;
            alert(tempLogoLeft.src);
            alert(tempLogoLeftWidth);
            alert(tempLogoLeftHeight);
            return true;
        }
        tempLogoLeft = new Image();
        tempLogoLeft.onload = tempLogoGetWH;
//this is not important I just put anything to make it work the key is where alerts are
        if (localStorage.settLogoLeftPath) {
            tempLogoLeft.src = 'http://cdn.sstatic.net/img/favicons-sprite16.png?v=b8d3dc7bcd05e3ba58eb1089d4838b9c'; 
        }
        else {
            tempLogoLeft.src = "http://cdn.sstatic.net/img/favicons-sprite16.png?v=b8d3dc7bcd05e3ba58eb1089d4838b9c";
        } 
        
    }
}
&#13;
&#13;
&#13;