javascript 在页面向下传递时触发 JQuery 函数

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

Trigger JQuery function when passed half way down the page

javascriptjquery

提问by steve

Is there a way to tell if you have scrolled passed the center of the web page or in other words, when you have scrolled passed exactly half of the web page and your scrollbar is situated in the lower half of the browser window?

有没有办法判断您是否滚动通过了网页的中心,或者换句话说,当您滚动通过了网页的一半并且您的滚动条位于浏览器窗口的下半部分时?

I want to be able to trigger this: $('.pineapple-man').show(); when I have scrolled down passed half of the page?

我希望能够触发这个: $('.pineapple-man').show(); 当我向下滚动页面的一半时?

Is this possible at all?

这可能吗?

Your help would be so kind!

你的帮助会非常好!

回答by Jawa

You can get the pixel amount of an element has been scrolled by using .scrollTop(). To listen to scroll events use .scroll().

您可以使用 获取已滚动元素的像素数量.scrollTop()。要收听滚动事件,请使用.scroll().

When you want to identify the halfway, use height of the scroll:

当您要识别中途时,请使用滚动的高度:

$(window).scroll(function () { 
  if ($(window).scrollTop() > $('body').height() / 2) {
    $('.pineapple-man').show();
  } 
});

If you are scrolling some other element than the whole window/body, please feel free to change the selectors.

如果您滚动的是整个窗口/正文以外的其他元素,请随时更改选择器。

To make the showing one-timer, add the removal of scrollevent listener, by adding the following after the .show()call:

为了使显示成为一次性的scroll,通过在.show()调用后添加以下内容来添加事件侦听器的删除:

$(window).unbind('scroll');

回答by usmanali

I guess you want to do something like this:

我猜你想做这样的事情:

if($(document).scrollTop() > $(document).height()/2){
   $('.pineapple-man').show();
}

where scrollTop()gets the current horizontal position and height()defines the document height.

wherescrollTop()获取当前水平位置并height()定义文档高度。

回答by Sjoerd

See the scrollevent and the scrollTopmethod.

查看滚动事件和scrollTop方法。

回答by Geeo

you can use the focus event if you scroll down to it (just like jQuery uses for their comments)

如果向下滚动到它,您可以使用焦点事件(就像 jQuery 用于他们的评论一样)

jQuery('selector').focus(function() {
  jQuery('.page').show();
});