我想在每个 div 到达顶部时提醒颜色名称。
$(function(){
console.log($('#one').offset());
console.log($('#two').offset());
console.log($('#three').offset());
console.log($('#four').offset());
$(window).scroll(function(){
$('.common').each(function(index, element) {
var getId = $(this).attr('id');
if($('#' + getId).offset().top === $(this).offset().top){
console.log($(this).attr('id'));
}
});
});
});
body {
float: left;
width: 100%;
}
.common {
width: 100%;
float: left;
height: 700px;
margin-bottom:10px;
}
#one {
background:red;
}
#two {
background:blue;
}
#three {
background:green;
}
#four {
background:black;
}
<div class="common" id="one"></div>
<div class="common" id="two"></div>
<div class="common" id="three"></div>
<div class="common" id="four"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
最佳答案
在这个版本中,我使用了 this.getBoundingClientRect().top
并检查它是否小于或等于零,即在视口(viewport)的顶部或之外。我们以相反的顺序循环遍历面板,以便我们可以在面板位于视口(viewport)顶部时立即停止。这是您要找的吗?
$(function(){
$(window).scroll(function(){
$($('.common').get().reverse()).each(function(index, element) {
var getId = $(this).attr('id');
if(this.getBoundingClientRect().top <= 0){
console.log(getId);
return false; // This breaks the jQuery `each` loop.
}
});
});
});
body {
float: left;
width: 100%;
}
.common {
width: 100%;
float: left;
height: 700px;
margin-bottom:10px;
}
#one {
background:red;
}
#two {
background:blue;
}
#three {
background:green;
}
#four {
background:black;
}
<div class="common" id="one"></div>
<div class="common" id="two"></div>
<div class="common" id="three"></div>
<div class="common" id="four"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
如果您的意思是您只想在面板到达顶部时收到一次提醒,然后不再提醒,您可以尝试将比较设置为 ===
而不是 <=
,但你可能永远不会看到它着火,因为 scroll
当面板恰好位于视口(viewport)顶部时,事件可能不会发生。
在这种情况下,您可以改用 IntersectionObserver
API .
关于jquery - 我想在每个 div 到达顶部时提醒颜色名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48555036/