javascript中的图像对象不返回宽度和高度

时间:2015-03-24 05:13:15

标签: javascript html image dom caching

我正在为图片轮播编写一个javascript代码,访问者可以点击图片。

出于某种原因,image对象为width,height,naturalWdith或naturalHeight返回0。此外,每次重新加载浏览器时,引用到图像对象的变量(nextImg)在DOM和图像对象之间发生变化。

问题出在loadImg函数中,这是代码中的最后一个函数。我为上下文包含了代码的其他部分。

var imgArray = document.querySelectorAll("#container img");
var current = 0; //index for imgArray

var nextImg = new Image();

var imgName;

function moveToNextImg(){
    //increment index to access next image in the array
    if(current === imgArray.length-1){
        current = 0;
    }
    else{
        current++;
    }
    updateIndex();

    //Fade out current image and execute loadImg after animation. 
    $("#imgWrapper").fadeOut("slow",loadImg);
 }

function loadImg(){

//imgArray contains <img> DOM, which are thumbnail images.  
    imgName = imgArray[current].getAttribute("src");

//Hi-res file names need "_Thumb" removed from from the thumbnail image file names. 
    nextImg.src = imgName.replace("_Thumb","");

    h = imgArray[current].naturalHeight;
    w = nextImg.naturalWidth; // returns 0, WHY?

    nextImg.id = "currentImg";

//Find out if the image if portrait or landscape orientation. Compare image height and width.   
    if((nextImg.height) > (nextImg.width)){
         //nextImg.height and nextImg.width are both 0. WHY??
        // console.log("portrait")
        nextImg.style.width = "32.5%"
    }

    else{
        nextImg.style.width = '750px';  
    }
        //Fadein the image.
        $("#imgWrapper").fadeIn("slow")

    }

0 个答案:

没有答案