[英]How can I print scrolltop() value 0 when scroll reaches top of the div
I have 5 div's on the same page. 我在同一页面上有5个div。 All div's have same class name 'post' and same height '600px'.
所有div都具有相同的类名“ post”和相同的高度“ 600px”。 So what I want is when I scroll any div among 5 div and when it reaches to the top of the div it should alert the value 0.
所以我想要的是当我在5 div中滚动任何div时,当它到达div的顶部时,它应该警告值0。
Trouble is When I scroll div2, div3, div4, div5 to the top. 问题是当我将div2,div3,div4,div5滚动到顶部时。 It did not print value '0'.
它没有打印值“ 0”。 But when I scroll div1 to the top and then if I scroll any other div's it shows '0'.
但是,当我将div1滚动到顶部,然后滚动其他div时,它显示为“ 0”。 I need to print '0' no matter which div I am scrolling first.
无论我首先滚动哪个div,我都需要打印'0'。 Why is it happening.
为什么会这样呢。 See the comment section for jsfiddle code.
有关jsfiddle代码的信息,请参见注释部分。 thanks in advance.
提前致谢。
Demo 演示版
$("window").load()
{
$('.post').scrollTop($('.post').height())
}
$('.post').scroll(function() {
if($('.post').scrollTop()==0)
{
alert('0');
}
});
Change 更改
if($('.post').scrollTop()==0)
{
alert('0');
}
to 至
if($(this).scrollTop()==0)
{
alert('0');
}
$('.post').scrollTop()
will give the value of the first div
(first found element). $('.post').scrollTop()
将给出第一个div
(第一个找到的元素)的值。 If the value of the first div
is 0, $('.post').scrollTop() == 0
will be always true
, even though you're scrolling other div
. 如果第一个
div
值为0,则即使滚动其他div
, $('.post').scrollTop() == 0
也将始终为true
。
You are always selecting first div. 您总是选择第一格。 This is why you are getting that result.
这就是为什么您得到该结果的原因。
In this code: 在此代码中:
if($('.post').scrollTop()==0)
{
alert('0');
}
$('.post').scrollTop() will return first found element. $('。post')。scrollTop()将返回第一个找到的元素。
Try this: 尝试这个:
$('.post').scroll(function() {
$('.post').each(function() {
if($(this).scrollTop()==0)
{
alert('0');
}
});
});
Wrap your post
divs in a parent, and iterate through children. 将您的
post
div包装在父母中,然后遍历孩子。 Then use this
keyword to identify which child div you're scrolling: 然后使用
this
关键字来标识要滚动的子div:
$('#allPosts').children().scroll(function () {
if ($(this).scrollTop() === 0) {
alert('0');
}
});
All you need is: 所有你需要的是:
$(".post").scroll(function () {
if ($(this).scrollTop() == 0) {
alert('0');
}
});
Fiddle: http://jsfiddle.net/052xntw9/19/ 小提琴: http : //jsfiddle.net/052xntw9/19/
This will attach an event listener to each div, and the $(this) refers specifically to that div (instead of the first div). 这会将事件侦听器附加到每个div,而$(this)专门引用该div(而不是第一个div)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.