javascript 将函数绑定到窗口调整大小和窗口滚动,但也立即调用它
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8932505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bind function to window resize and window scroll but also invoke it immediately
提问by ?ime Vidas
So, on a web-page there are some components that have to be re-positioned whenever the browser window is re-sized or scrolled.
因此,在网页上有一些组件必须在浏览器窗口调整大小或滚动时重新定位。
$( window ).on( 'resize scroll', reposition );
where reposition
is the function that does that.
执行此reposition
操作的函数在哪里。
However, that function has to be invoked immediately too. (By immediately, I mean on page initialization - inside DOM-ready.) This needs to be done to set up the initial positions of the components.
但是,该函数也必须立即调用。(立即,我的意思是在页面初始化 - 在 DOM-ready 中。)这需要完成以设置组件的初始位置。
I'm currently doing it like so:
我目前正在这样做:
$( window ).on( 'resize scroll', reposition );
reposition();
I noticed that this also works:
我注意到这也有效:
$( window ).on( 'resize scroll load', reposition );
I believe this is reliable - the load
is never fired before the DOMContentLoaded
event.
我相信这是可靠的 -load
在DOMContentLoaded
事件发生之前从未被解雇。
But this delays the execution until after all page resources have been loaded (which could take a few seconds depending on how many images there are on the page). Is there any way to tell jQuery that the bound function should be invoked immediately too?
但这会延迟执行,直到所有页面资源都已加载(这可能需要几秒钟,具体取决于页面上有多少图像)。有什么方法可以告诉 jQuery 绑定函数也应该立即调用吗?
Like:
喜欢:
$( window ).on( 'resize scroll now', reposition );
or
或者
$( window ).on( 'resize scroll ()', reposition );
These examples are of course invalid, but I was wondering if jQuery's on
method has such functionality. I guess, I could manually implement this functionality into on
, but I'd like to first check if it has that already...
这些例子当然是无效的,但我想知道 jQuery 的on
方法是否有这样的功能。我想,我可以手动将此功能实现到on
,但我想首先检查它是否已经...
回答by qwertymk
You can do something like this:
你可以这样做:
$(window).on('resize scroll', reposition).trigger('scroll');
To set and trigger an event callback.
设置和触发事件回调。
Although you should be setting this in the $(document).ready just to be safe. Basically your code should look something like this:
尽管您应该在 $(document).ready 中设置它以确保安全。基本上你的代码应该是这样的:
$(document).ready(function() {
$(window).on('resize scroll', reposition).trigger('scroll');
});
So you're guaranteed that the DOM will be ready for you to mess around with
因此,您可以保证 DOM 已准备好供您使用