Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

javascript - Trigger JQuery function when passed half way down the page

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?

Is this possible at all?

Your help would be so kind!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can get the pixel amount of an element has been scrolled by using .scrollTop(). To listen to scroll events use .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 scroll event listener, by adding the following after the .show() call:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...