jQuery resize function doesn't work on page load

拥有回忆 提交于 2019-11-26 09:11:41

问题


How do I get this function to not only run on window resize but also on initial page load?

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

回答1:


You'll want to use:

$(document).ready(function() { /* your code */ });

To make something happen onload. If you want something to work onload and onresize, you should do:

onResize = function() { /* your code */ }

$(document).ready(onResize);

$(window).bind('resize', onResize);



回答2:


I think the best solution is just to bind it to the load and resize event:

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



回答3:


This behavior is by design.

You should put your code into a named function, then call the function.

For example:

function onResize() { ... }

$(onResize);
$(window).resize(onresize);

Alternatively, you can make a plugin to automatically bind and execute a handler:

$.fn.bindAndExec = function(eventNames, handler) {
    this.bind(eventNames, handler).each(handler);
};

$(window).bindAndExec('resize', function() { ... });

Note that it won't work correctly if the handler uses the event object, and that it doesn't cover every overload of the bind method.




回答4:


$(document).ready(onResize);
$(window).bind('resize', onResize);

didn't work with me.

Try

$(window).load('resize', onResize);
$(window).bind('resize', onResize);

instead.

(I know this question is old, but google sent me here, so...)




回答5:


Another approach, you can simply setup a handler, and spoof a resize event yourself:

// Bind resize event handler through some form or fashion
$(window).resize(function(){
  alert('Resized!');
});

// Trigger/spoof a 'resize' event manually
$(window).trigger('resize');


来源:https://stackoverflow.com/questions/2597152/jquery-resize-function-doesnt-work-on-page-load

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