javascript - 每次点击页面顶部时如何检测正确的div数据属性
问题描述
我正在处理下面的代码。为什么我无法在向下或向上滚动时检测到哪个 div 到达页面顶部?
$(window).scroll(function() {
$(".container").each(function() {
var $that = $(this);
var po = $(this).offset().top;
if (po >= 0 && po <= 300) {
console.log($that.data('map'));
}
});
});
.container {
height: 690px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container" data-map="One">One</div>
<div class="container" data-map="Two">Tow</div>
<div class="container" data-map="Three">Three</div>
<div class="container" data-map="Four">Four</div>
<div class="container" data-map="Five">Five</div>
解决方案
你需要使用$(window).scrollTop();
以及$that.outerHeight()
$(window).scroll(function() {
var windowScrollTop = $(this).scrollTop(); // window scroll top
$(".container").each(function() {
var $that = $(this);
var po = $that.offset().top;
var poHeight = $that.outerHeight(true); // the height of the element
var distanceTop = 100; // the distance from top to run the action .. it can be 0 if you want to run the action when the element hit the 0 top
if (windowScrollTop + distanceTop >= po && windowScrollTop + distanceTop <= po + poHeight) {
if(!$that.hasClass('red')){ // if element dosen't has class red
console.log($that.data('map'));
$(".container").not($that).removeClass('red'); // remove red class from all
$that.addClass('red'); // add red class to $that
}
}
});
}).scroll(); // run the scroll onload
.container {
height: 690px;
}
.container.red{
background : red;
color : #fff;
font-size: 30px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container" data-map="One">One</div>
<div class="container" data-map="Two">Two</div>
<div class="container" data-map="Three">Three</div>
<div class="container" data-map="Four">Four</div>
<div class="container" data-map="Five">Five</div>
推荐阅读
- c# - C# DateTime 如何确定现在和今天的时间
- excel - 如何通过VBA在excel中创建具有特殊格式的字符串列表
- postgresql - 如何对搜索结果进行分页?
- javascript - Jquery在数据表上使用ajax渲染Json内容
- logstash - 将日志文件合并到beats中的一个主日志文件并发送到logstash
- flutter - 如何使用下拉按钮显示通过 API (GET) 提取的数据
- c# - C# ssh 连接到 HP 交换机(绕过“更多”)
- powershell - 如何编写 Powershell 逻辑以从包含不同字符的行中提取特定字段
- node.js - 如何使用mongoDb获取字符串中关键字的出现次数
- javascript - 带有嵌套 td 子项的嵌套表,没有 Json 的标头