仅当滚动位置在2点之间时才使用jQuery显示div [英] Use jQuery to show a div only when scroll position is between 2 points

查看:78
本文介绍了仅当滚动位置在2点之间时才使用jQuery显示div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出如何使div(#tips)在用户滚动到其包含的div高度的第二个四分之一(#wrap)时显示,然后在用户滚动到div的高度的第二个季度时消失上个季度.就像这样:

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:

第一季度-#tips隐藏
第二季度-#tips可见
第三季度-#tips可见
第四季度-#tips隐藏了

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

我几乎完全不是jQuery的新手,但是到目前为止,我是这样的:

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");
 }
}

这是我感到困惑的地方.如何检查滚动位置是否> $ quarterwrapHeight但< $ threequarterswrapHeight?

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!

谢谢.

推荐答案

您好,我在此处发布了演示 ...唯一的问题是,如果#wrap div不够高,则窗口的顶部永远不会达到3/4的高度,因此工具提示不会消失.这是代码:

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');
  }
 });
})

我使用了height(),但是您可以使用outerHeight() ...我忘了在演示中进行更改,因为最初我使用的是body而不是#wrap.

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.

另一个问题是,如果#wrap不在页面顶部.如果它进一步下降,则必须从scrollTop减去它在页面上的位置:

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点之间时才使用jQuery显示div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆