簡體   English   中英

JavaScript Image()。width返回0

[英]JavaScript Image().width returns 0

我需要使用display:none得到圖像的寬度和高度,我得到寬度和高度0.這是我的代碼:

for (i = 0; i <= slideCount; ++i) {
            imgPath = slideshow.eq(i).attr("src");
            imgEle = new Image();
            imgEle.src = imgPath;

            imgEle.addEventListener("load", function () {
                imgSize = [imgEle.width, imgEle.height];
                if ((imgSize[0]/imgSize[1]) > (boxSize[0]/boxSize[1])) {
                    slideshow.eq(i).css("height", "100%");
                }
                else {
                    slideshow.eq(i).css("width", "100%");
                }
            });
        }

我嘗試了onload = funcion() {}方法以及不檢查圖像是否已加載,但我仍然得到寬度和高度為0.當我在Chrome上啟動控制台並參考那些字段時,我得到了正確的值。

這是因為在循環中錯誤地使用了閉包變量,當執行加載處理程序時,變量imgEle引用最后一個圖像對象引用,而不是調用load事件的引用,所以當第一個元素被加載時最后一個元素可能尚未加載,因此imgEle.width / imgEle.height將返回0

相反,你可以使用this ,這將指在其被稱為Load事件處理程序中加載事件的元素

從我所看到的,你需要的是

slideshow.each(function () {
    var $this = $(this);
    var imgPath = $this.attr("src");
    var imgEle = new Image();
    imgEle.src = imgPath;

    imgEle.addEventListener("load", function () {
        var imgSize = [this.width, this.height];
        if ((imgSize[0] / imgSize[1]) > (boxSize[0] / boxSize[1])) {
            $this.css("height", "100%");
        } else {
            $this.css("width", "100%");
        }
    });
})

注意:數組索引從0...length-1因此你的循環條件<= slideCount; 可能不得不重新審視

每次循環運行時都會覆蓋imgEle 在其周圍包裝匿名函數以防止此問題。

for(var i = 0; i <= slideCount; ++i) {
    (function(i){
        var imgPath = slideshow.eq(i).attr("src");
        var imgEle = new Image();
        imgEle.src = imgPath;

        imgEle.addEventListener("load", function () {
            imgSize = [imgEle.width, imgEle.height];
            if ((imgSize[0]/imgSize[1]) > (boxSize[0]/boxSize[1])) {
                slideshow.eq(i).css("height", "100%");
            }
            else {
                slideshow.eq(i).css("width", "100%");
            }
        });
    })(i);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM