当窗口大于 x 时以及调整窗口大小时运行脚本
我有一个 jQuery 脚本,仅当窗口宽度大于 1245px 时才运行该脚本。
if ($(window).width() > 1245) {
// script
}
这是出于响应性原因。但假设我在桌面上,并且从小于 1245px 的窗口开始;我希望能够调整它的大小并运行该函数,反之亦然,如果我从一个更大的窗口开始。
我尝试过像这样使用“调整大小”:
$(window).on('resize', function(){
var win = $(this); // this = window
if (win.height() > 1245) { /* ... */ }
}
但是我遇到了脚本未以初始窗口大小运行的问题,解决此问题的最佳方法是什么?
I have a jQuery script that I want to run only if the window is wider than 1245px.
if ($(window).width() > 1245) {
// script
}
This is for responsive reasons. But let's say I am on desktop and start with a window smaller than 1245px; I want to be able to resize it and run that function and vise versa if I start with a larger window.
I have tried using 'resize' like this:
$(window).on('resize', function(){
var win = $(this); // this = window
if (win.height() > 1245) { /* ... */ }
}
But I run into problems with the script not running at the initial window size, what's the best way to approach this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
还要将
load
添加到事件列表中:请注意,调整大小事件在调整窗口大小时会连续触发,因此例如,如果您在一秒钟内将其大小从 1000 调整到 1600 像素,它将触发 600 次。使用任何昂贵的功能都会使浏览器陷入困境。我建议使用“去抖动”技巧来调整事件大小。
Also add
load
to the list of events:Be advised that resize event is fired continuously while window is being resized so for example if you resize it from 1000 to 1600px in one second it would fire 600 times. Using any expensive function will bog down the browser. I recommend using "debouncing" trick for resize events.