简体   繁体   中英

Setting image position with javascript, not always placing correctly

I'm using the following code to position images on my page:

var adjustImages = function(){
    var monsters = [$("#m3"), $("#m4")];

    monsters[0].css('right', monsters[0].width() * -0.4 + "px");
    monsters[0].css('top', $("#divider-green").height() + $("#divider-orange").height() + (monsters[3].height() / 6) + "px");
    monsters[1].css('left', monsters[1].width() * -0.385 + "px");
    monsters[1].css('top', $("#divider-green").height() + $("#divider-orange").height() + $("#divider-red").height() + "px");
}

I'm then calling this function when the page loads, and when it's resized:

$(document).ready(function(){
    adjustImages();
});

window.onresize = function(event) {
    adjustImages();
};

The images are meant to be positioned on the window border (as in, part of the image is off the screen, part it off). This is done by setting right/left to a negative number (relative to the image size).

Sometimes when I refresh the page the images are placed correctly, however other times they are not over the border (but are rather positioned against the border (as if no left/right adjustment was applied). Does anyone know what the cause of this might be?

It looks like you aren't doing any check to see if the image is loaded before doing math based on it's width. That's probably what's causing the inconsistent behavior.

When an image is first created in the DOM, before it's loaded (and if it doesn't have one set directly), it's width and height are 0. What I would do is add a load event listener on your images and then call adjust.

You also want to call adjustImages() if one of the images already has a width greater than 0, because that means it's already loaded by the time the document is ready.

$(document).ready(function(){
    $('#m3, #m4').one('load', function () {
        adjustImages();
    });

    if ($('#m3').width > 0 || $('#m4').width > 0) {
        adjustImages();
    }
});

Now, that code snippet has a bit of a bug because it'll fire once either is loaded, not when both are loaded. You'll want to tweak it, and probably even separate them out so you're doing things individually for each, but it should give you the idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM