如何正确(现代)地监控窗口调整大小事件,使其在Firefox,WebKit和Internet Explorer中均可正常工作?
你能同时开启/关闭两个滚动条吗?
对于此事,jQuery 已经有了一个内置方法:
$(window).resize(function () { /* do something */ });
为了提高用户界面的响应性,你可以考虑使用setTimeout在一定的毫秒数后调用你的代码,以下示例启发自这里:
function doSomething() {
alert("I'm done resizing for the moment");
};
var resizeTimer;
$(window).resize(function() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(doSomething, 100);
});
$('.button').on({ click: function(){ /* 你的代码 */ $(window).trigger('resize') })
- Zack Zatkin-Gold$(window).bind('resize', function () {
alert('resize');
});
这是一种非使用jQuery的方式来监听resize事件:
window.addEventListener('resize', function(event){
// do stuff here
});
它适用于所有现代浏览器。它不会为你限制任何内容。 这里有一个示例,展示了它的效果。
很抱歉又翻出了一个旧的帖子,但如果有人不想使用jQuery,可以使用以下代码:
function foo(){....};
window.onresize=foo;
使用 jQuery 1.9.1,我刚刚发现尽管在技术上相同,但这在 IE10 中不能正常工作(但在 Firefox 中可以):
// did not work in IE10
$(function() {
$(window).resize(CmsContent.adjustSize);
});
虽然这在两个浏览器中都有效:
// did work in IE10
$(function() {
$(window).bind('resize', function() {
CmsContent.adjustSize();
};
});
编辑:.resize()
更改为.bind('resize')
还是添加匿名函数?我认为是第二个。) - WraithKennyadjustSize
方法失去了它的上下文this
,而第二个调用CmsContent.adjustSize()
保留了this
,即this === CmsContent
。如果在adjustSize
方法中需要CmsContent
实例,则第一种情况将失败。第二种情况适用于每种函数调用,因此建议始终传递匿名函数。 - Henry BlythjQuery
默认提供$(window).resize()
函数:
<script type="text/javascript">
// function for resize of div/span elements
var $window = $( window ),
$rightPanelData = $( '.rightPanelData' )
$leftPanelData = $( '.leftPanelData' );
//jQuery window resize call/event
$window.resize(function resizeScreen() {
// console.log('window is resizing');
// here I am resizing my div class height
$rightPanelData.css( 'height', $window.height() - 166 );
$leftPanelData.css ( 'height', $window.height() - 236 );
});
</script>
http://www.paulirish.com/2009/throttled-smartresize-jquery-event-handler/
请务必查看演示以查看差异。
以下是完整的函数。
(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...
});
希望这对jQuery有所帮助
首先定义一个函数,如果已经存在函数则跳过下一步。
function someFun() {
//use your code
}
浏览器调整大小使用如下。
$(window).on('resize', function () {
someFun(); //call your function.
});
window.dispatchEvent(new Event('resize'));
可以触发 JavaScript 中的窗口调整大小事件。详情请参考 https://dev59.com/i3I-5IYBdhLWcg3whImk - Dylan Valade