jquery - 我想在每个 div 到达顶部时提醒颜色名称

标签 jquery html css

我想在每个 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/

相关文章:

html - 尝试使用自定义 Css/html 时出现 Shopify + Parallax 主题问题

html - 使用 Bootstrap 将侧边栏拆分为围绕主要内容的顶部和底部

html - 可滚动表在 IE8 中有额外的不需要的空间

html - 在浏览器 Firefox 中 span 和它的 pseudo::before 之间重叠

jquery - 是什么导致布局中断?尝试做一个水平布局的网站

javascript - jquery p :last-child not working

jquery - Bootstrap 的视差

javascript - svg img 上的时钟淡入动画

javascript - 通过 ajax 调用动态添加的内容不能用 jquery 定位

html - 让一个词成为单选按钮?