当用户结束调整浏览器窗口大小时,jQuery 或 JavaScript 是否可以触发一个函数?
换句话说:
目前我只能在用户开始使用 jQuery 调整窗口大小时触发一个事件
您可以使用 .resize()获取每次宽度/高度实际变化的结果,如下所示:
.resize()
$(window).resize(function() { //resize just happened, pixels changed });
您可以在这里查看一个工作演示 ,它获取新的高度/宽度值并在页面中更新它们,以便您查看。请记住,事件并不是真正的 开始或 结束,它只是“发生”当一个调整发生... 没有什么可以说另一个不会发生。
编辑: 通过评论,似乎你想要一个类似于“ on-end”事件的东西,你找到的解决方案做到了这一点,除了一些例外(你不能以跨浏览器的方式区分鼠标向上和暂停,对于 结束和 暂停也是一样)。你可以 创造的事件,虽然,使它有点干净,像这样:
$(window).resize(function() { if(this.resizeTO) clearTimeout(this.resizeTO); this.resizeTO = setTimeout(function() { $(this).trigger('resizeEnd'); }, 500); });
你可以在某个地方放一个基本文件,无论你想做什么... 然后你可以绑定到你触发的新的 resizeEnd事件,像这样:
resizeEnd
$(window).bind('resizeEnd', function() { //do something, window hasn't changed size in 500ms });
您可以在这里看到这种方法的工作演示
这可以通过 JavaScript 中 GlobalEventHandlers 接口的 放大属性来实现,方法是为 放大属性分配一个函数,如下所示:
window.onresize = functionRef;
下面的代码片段通过控制台记录调整窗口大小时窗口的 innerWidth 和 innerHeight 来演示这一点
function resize() { console.log("height: ", window.innerHeight, "px"); console.log("width: ", window.innerWidth, "px"); } window.onresize = resize;
<p>In order for this code snippet to work as intended, you will need to either shrink your browser window down to the size of this code snippet, or fullscreen this code snippet and resize from there.</p>
另一种方法是只使用 JavaScript:
window.addEventListener('resize', functionName);
每次大小变化时就会触发,就像另一个答案一样。
functionName是调整窗口大小时正在执行的函数的名称(不需要末尾的括号)。
functionName
如果你只想检查滚动结束的时候,在 Vanilla JS 中,你可以想出这样一个解决方案:
超级紧凑型
var t window.onresize = () => { clearTimeout(t) t = setTimeout(() => { resEnded() }, 500) } function resEnded() { console.log('ended') }
所有3种可能的组合在一起(ES6)
var t window.onresize = () => { resizing(this, this.innerWidth, this.innerHeight) //1 if (typeof t == 'undefined') resStarted() //2 clearTimeout(t); t = setTimeout(() => { t = undefined; resEnded() }, 500) //3 } function resizing(target, w, h) { console.log(`Youre resizing: width ${w} height ${h}`) } function resStarted() { console.log('Resize Started') } function resEnded() { console.log('Resize Ended') }