在窗口事件上运行 Jquery 函数:加载、调整大小和滚动?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15665231/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:32:50  来源:igfitidea点击:

Run Jquery function on window events: load, resize, and scroll?

javascriptjqueryhtml

提问by user2152326

How do I run a jquery function on window events: load, resize, and scroll?

如何在窗口事件上运行 jquery 函数:加载、调整大小和滚动?

Here is my code I'm trying to detect if a div is viewable and then if it is run some ajax code...

这是我的代码,我试图检测一个 div 是否可见,然后它是否运行了一些 ajax 代码......



<script>
function topInViewport(element) {
    return $(element).offset().top >= $(window).scrollTop() && $(element).offset().top          <= $(window).scrollTop() + $(window).height();
 }

 </script>

<script>
topInViewport($("#mydivname"))
{
// ajax code goes here
}

回答by mattytommo

You can use the following. They all wrap the windowobject into a jQuery object.

您可以使用以下内容。它们都将window对象包装成一个 jQuery 对象。

Load:

加载:

$(window).load(function () {
    topInViewport($("#mydivname"))
});

Resize:

调整大小:

$(window).resize(function () {
   topInViewport($("#mydivname"))
});

Scroll

滚动

$(window).scroll(function () {
    topInViewport($("#mydivname"))
});

Or bind to them all using on:

或者使用on以下方法将它们全部绑定:

$(window).on("load resize scroll",function(e){
    topInViewport($("#mydivname"))
});

回答by SachinGutte

You can bind listeners to one common functions -

您可以将侦听器绑定到一个常用功能 -

$(window).bind("load resize scroll",function(e){
  // do stuff
});

Or another way -

或者换一种方式——

$(window).bind({
     load:function(){

     },
     resize:function(){

     },
     scroll:function(){

    }
});

Alternatively, instead of using .bind()you can use .on()as bind directly maps to on(). And maybe .bind()won't be there in future jquery versions.

或者,.bind()您可以使用.on()as bind 直接映射到on(). 并且可能.bind()不会在未来的 jquery 版本中出现。

$(window).on({
     load:function(){

     },
     resize:function(){

     },
     scroll:function(){

    }
});

回答by bipen

just call your function inside the events.

只需在事件中调用您的函数。

load:

加载:

$(document).ready(function(){  // or  $(window).load(function(){
    topInViewport($(mydivname));
});

resize:

调整大小:

$(window).resize(function () {
    topInViewport($(mydivname));
});

scroll:

滚动:

$(window).scroll(function () {
    topInViewport($(mydivname));
});

or bind all event in one function

或在一个函数中绑定所有事件

$(window).on("load scroll resize",function(e){