使用jQuery捕获调整浏览器窗口大小时的事件,然后执行某些操作。 在下面的示例中,它记录了窗口的新大小。
2013年6月5日更新:请参阅下面的反跳方法,以更智能地调整窗口大小!
//capture window resize
$(window).bind('resize', function(e)
{
var win = $(this),
w = win.width(),
h = win.height();
console.log('window resized to: ' + w + ' by ' + h);
});
//output: window resized to: 1598 by 521
刷新浏览器页面大小
一个漂亮的跨浏览器IE8 +解决方案。
//this is in a timeout so it works in IE8
setTimeout(function()
{
$(window).bind('resize', function(e)
{
if(window.RT) clearTimeout(window.RT);
window.RT = setTimeout(function()
{
this.location.reload(false); /* false to get page from cache */
}, 300);
});
}, 1000);
调整窗口大小时重新定位导航栏的示例
调整窗口大小后,移动导航菜单栏。 稍微延迟300毫秒,但这是为了防止在调整浏览器大小时递归调用重新定位。
(function($,W)
{
//DOM Ready
$(function()
{
//responsive main nav absolute top position relative to window height
function repositionMainNav()
{
var newT = W.innerHeight - 300;
newT = (newT < 165) ? 165 : newT; //min top
newT = (newT > 550) ? 550 : newT; //max top
// console.log(newT);
$('#navbar').css('top', newT);
}
repositionMainNav();
$(W).bind('resize', function(e)
{
if(W.RT) clearTimeout(W.RT);
W.RT = setTimeout(function()
{
//recalculate the vertical position of the main nav
repositionMainNav();
}, 300);
});
});
})(jQuery, window);
宣布“更智能”的窗口调整大小事件
感谢曾经杰出的保罗爱尔兰先生(Paul Irish)在他的退役职位上观看演示的实际情况 。
(function($,sr){
// debouncing function from John Hann
// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
var debounce = function (func, threshold, execAsap) {
var timeout;
return function debounced () {
var obj = this, args = arguments;
function delayed () {
if (!execAsap)
func.apply(obj, args);
timeout = null;
};
if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 100);
};
}
// smartresize
jQuery.fn[sr] = function(fn){ return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };
})(jQuery,'smartresize');
// usage:
$(window).smartresize(function(){
// code that takes it easy...
});
From: https://www.sitepoint.com/jquery-capture-window-resize/