Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

jquery - script not working on document.ready in Safari & Chrome (FF okay), but works on document.resize

I have the following jquery script to resize an image and give it a left margin to horizontally center it. The script works perfectly in FF, but in Safari and Chrome I have problems.

Safari & Chrome prob: the image resizes okay, but the leftMargin appears to be set before the image is resized resulting in an image that is pushed much too far left. This problem occurs only on document.ready. When resizing the browser, the script works fine.

function imageresize() {
    var h = $(window).height(),
        w = $(window).width(),
        newHeight = h * 0.5,
        newTopMargin = newHeight * 0.12;

        $('img.resize').css({'height' : newHeight + 'px', 'margin-top' : '-' + newTopMargin + 'px'});
    var leftMargin = (w - ($('img.resize').width()))/2;
        $('img.resize').css('margin-left', leftMargin + 'px');

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

$(window).resize(function() {
  imageresize();
});

The script is placed before </body>.

Any assistance would be much appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The document ready event can fire before images have finished loading. Try binding to window, or images' load event instead.

$(window).load(function() {
  imageresize();
});

// or

$('img').load(function() {
  imageresize();
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...