仅当滚动位置在 2 点之间时,才使用 jQuery 显示 div [英] Use jQuery to show a div only when scroll position is between 2 points
问题描述
我正在尝试研究如何在用户滚动到包含 div 高度 (#wrap) 的第二个四分之一时显示 div (#tips),然后在用户滚动到上个季度.所以它会是这样的:
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 可见
第 4 季度 - #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 但 <$四分之三包裹高度?
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屋!