Use jQuery to show a div only when scroll position

2019-01-13 17:25发布

问题:

I'm trying to work out how to get a div (#tips) to appear when the user scrolls into the 2nd quarter of its containing div's height (#wrap), and then have it disappear when the user scrolls into the last quarter. So it would be like this:

1st quarter - #tips is hidden
2nd quarter - #tips is visible
3rd quarter - #tips is visible
4th quarter - #tips is hidden

I'm almost completely new to jQuery but what I've got so far is this:

function addKeyboardNavigation(){
 // get the height of #wrap
 var $wrapHeight = $('#wrap').outerHeight()
 // get 1/4 of wrapHeight
 var $quarterwrapHeight = ($wrapHeight)/4
 // get 3/4 of wrapHeight
 var $threequarterswrapHeight = 3*($wrapHeight)
 // check if we're over a quarter down the page
 if( $(window).scrollTop() > $quarterwrapHeight ){
  // if we are show keyboardTips
  $("#tips").fadeIn("slow");
 }
}

This is where I get confused. How can I check if the scroll position is > $quarterwrapHeight but < $threequarterswrapHeight?

To make it run I've been using:

// Run addKeyboardNavigation on scroll
$(window).scroll(function(){
 addKeyboardNavigation();
});

Any help or suggestions would be greatly appreciated!

Thanks.

回答1:

Hi I posted a demo here... the only problem is if your #wrap div isn't tall enough, the top of the window will never get to the 3/4 height, so the tooltip won't fade out. Here is the code:

$(document).ready(function(){
 $(window).scroll(function(){
  // get the height of #wrap
  var h = $('#wrap').height();
  var y = $(window).scrollTop();
  if( y > (h*.25) && y < (h*.75) ){
   // if we are show keyboardTips
   $("#tips").fadeIn("slow");
  } else {
   $('#tips').fadeOut('slow');
  }
 });
})

I used height() but you can use outerHeight()... I forgot to change it in the demo because originally I was using the body instead of the #wrap.

Another problem would be if the #wrap isn't located at the top of the page. If it's further down, then you'll have to subtract it's position on the page from the scrollTop:

var y = $(window).scrollTop() - $('#wrap').position().top;


回答2:

How about:

if(($(window).scrollTop() > $quarterwrapHeight) && ($(window).scrollTop() < $threequarterswrapHeight)){
   $("#tips").fadeIn("slow");
} else {
   $("#tips").fadeOut("slow");
}


标签: jquery scroll