<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.my-div {
height: 2000px;
background-color: #ccc;
}
.active {
background-color: #f00;
}
</style>
</head>
<body>
<div class="my-div"></div>
<script>
$(window).scroll(function() {
var scrollDistance = $(window).scrollTop();
var targetDiv = $('.my-div');
var targetPosition = targetDiv.offset().top;
var triggerDistance = 200; // 设置触发添加active属性的滑动距离
if (scrollDistance >= targetPosition - triggerDistance) {
targetDiv.addClass('active');
} else {
targetDiv.removeClass('active');
}
var windowHeight = $(window).height();
if (scrollDistance === 0) {
targetDiv.removeClass('active');
}
});
</script>
</body>
</html>
jqurey实现网页向下滑动一定距离后,给div添加active属性,滑动到顶部时删除active属性
最新推荐文章于 2024-07-12 16:27:40 发布