jQuery function triggered on window resize but not on page load

僤鯓⒐⒋嵵緔 提交于 2019-12-05 21:36:27
$(document).ready(function(){
    doResize();
    $(window).on('resize', doResize);
});

function doResize() {
    $('.img-holder').css({
        position:'absolute',
        left: ($(window).width() - $('.img-holder').outerWidth())/2,
        top: ($(window).height() - $('.img-holder').outerHeight())/2
    });
}

FIDDLE

Try this:

function adoptToSize() {
    $('.img-holder').css({
        position:'absolute',
        left: ($(window).width() - $('.img-holder').outerWidth())/2,
        top: ($(window).height() - $('.img-holder').outerHeight())/2
    });
}

$(document).ready(adoptToSize);
$(window).resize(adoptToSize);

Why not

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

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

function resize() {
    $('.img-holder').css({
        position:'absolute',
        left: ($(window).width() - $('.img-holder').outerWidth())/2,
        top: ($(window).height() - $('.img-holder').outerHeight())/2
    });
}

Try this. You cannot call a callback function like these.

$(document).ready(function(){

$(window).resize(function(){

$('.img-holder').css({
    position:'absolute',
    left: ($(window).width() - $('.img-holder').outerWidth())/2,
    top: ($(window).height() - $('.img-holder').outerHeight())/2
});

});

$('.img-holder').css({
    position:'absolute',
    left: ($(window).width() - $('.img-holder').outerWidth())/2,
    top: ($(window).height() - $('.img-holder').outerHeight())/2
});

});

Try something like:

+function($, window){
  var resizeWin = function(){
      $('.img-holder').css({
          position:'absolute',
          left: ($(window).width() - $('.img-holder').outerWidth())/2,
          top: ($(window).height() - $('.img-holder').outerHeight())/2
      });
  }

  $(function(){ resizeWin() });
  $(window).bind('resize',resizeWin);
}(jQuery, window, undefined);

Remember that $(document).ready happens after the DOM is ready, but before all content is loaded.

Your <img /> may not have loaded when you first trigger the resize function...
Try using the document's load event, or the image's load event.

The best solution here, however, is to give the image a fixed size:

<img src="img/test.jpg" style="width:800px;height:519px;" />

or:

.img-holder img {width:800px;height:519px;}

Bind it both the load and resize event at the same time as below:

$(window).on('load resize', function () {
// your code
});

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!