开发者

The image's dimension is different from when it's loading and after it loads

I have a page that loads a lot of fairly large i开发者_C百科mages (about 200 of 100Kb images [about 600 x 400 px]).

What I'm trying to do is manipulate the photo if it's in portrait, as opposed to landscape.

The problem I'm experiencing is that when i use javascript to grab a portrait photo's properties when it's loading, the height is significantly lower than what it should be, and the width is bigger than it should be. Specifically, a 75 x 100 image was considered as a 100 x 16. So when the function runs through this image, the image is considered landscape, not portrait, and skips over.

I had hard time identifying the problem, because the property shows it as a 75 x 100px image after it's done loading.

Is there a way to get around this problem? or run the function after all the images have loaded?


Run the function after it has loaded, You'd do it like this:

Using the DOM exclusively

var newImg = document.createElement('img');
newImg.src = "theImage.png";
newImg.alt = "Always specify an alternate text for accessibility, even if left blank";
newImg.onload = function () {
    //Image manipulation
};
galleryNode.appendChild(newImg); //Replace galleryNode with the parent element of your image.

Using innerHTML

galleryNode.innerHTML += "<img src='theImage.png' alt='' id='newImage1'/>";
var newImg = document.getElementById('newImage1');
newImg.onload = function () {
    //Image manipulation
};

Using jQuery

$('.gallery img').live('load',function () {
    //Image manipulation
});


Its always a good idea to run javascript after the page elements have finished loading. I usually do this in jQuery, like this:

$(function(){
  //code to run after load goes here
});

Otherwise, you can try modifying the body tag and giving it an onload attribute, like:

<body onload="myFunction();" >
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜