$(window).load OR $(window).scroll in the same function?

非 Y 不嫁゛ 提交于 2019-12-21 20:37:34

问题


I have implemented stickyfloat (http://plugins.jquery.com/files/stickyfloat_0.htm) on a site. It works great with one gotcha. The function triggers on $(window).scroll and not on $(window).load. I want it to trigger on either because I am linking to anchor points in the page (http://tre-stage.wdogsystems.com:8000/faq/#does-the-sale-of-my-receivables-have-a-negative-effect-on-my-credit-report) and I would like the side menu to appear when the page loads and not just when I initiate a scroll.

If you look at the page above, it's working just as I want it to. However, this is only because I've repeated the same function with a $(window).load. This seems highly inefficient to me. So, is there a way to chain the two together?

For example:

$(window).scroll || $(window).load (function () ...

回答1:


jQuery's .bind()help method allows multiple events bound at once.

$(window).bind('scroll load', function() {
    // code here triggers for both, scroll & load events
});



回答2:


just chain in the bind, like:

$(window).bind("scroll load", ...)

however it is very bad idea to attach to scroll event

a very good explanation why and a great solution: http://ejohn.org/blog/learning-from-twitter/




回答3:


Like this:

$(document).bind('ready load scroll', function() { ... });



回答4:


Why don't you just trigger a window scroll event on load? You could namespace your scroll event too to isolate it and have better access to it later...

$(window)
   .on('scroll.myscroll', function () {
      // do something on scroll event
   })
   .trigger('scroll.myscroll'); // trigger scroll event on pageload

But if you were actually wanting to run it on window load (ensuring the DOM is fully loaded incl. images etc) then the other examples mentioned are fine. But use the .on() method, rather than .bind().

$(window).on('scroll.myscroll load.myload', function () {
   // do something on scroll and load events
});


来源:https://stackoverflow.com/questions/4818156/window-load-or-window-scroll-in-the-same-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!