大家好,我试图在div触及浏览器顶部时将类添加到div中。 这样的页面上的特定div很容易
$window.scroll(function(){
var windowTop = $window.scrollTop(),
sectionTouchTop = $('.section').offset().top();
if( windowTop >= sectionTouchTop-90){
$('.section').addClass('hope');
}
});
但是我想要的是具有属性[touching =“”]的所有div通用的代码 当此attr的div触及浏览器顶部时,此attr的值将作为该div的类添加
$window.scroll(function(){
var windowTop = $window.scrollTop(),
sectionTouchTop = $('[touching]').offset().top();
if( windowTop >= sectionTouchTop-90){
$('[touching]').addClass( $(this).attr(touching) );
}
});
请帮忙。
答案 0 :(得分:3)
这是执行此操作的逻辑,请尝试运行以下代码段
$(window).on("scroll", () => {
$("[touching]").each(function() {
var className = $(this).attr("touching")
var offset = $(this).offset().top - $(window).scrollTop();
if (offset <= 0) {
$(this).addClass(className)
} else {
$(this).removeClass(className)
}
})
}).trigger("scroll")
* {
margin: 0;
padding: 0
}
.demo {
background-color: blue;
width: 50px;
height: 50px;
}
.offset {
height: 500px;
}
.green {
background-color: green;
}
.black {
background-color: black;
}
.orange {
background-color: orange;
}
.top {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="demo" touching="top"></div>
<div class="demo" touching="green"></div>
<div class="demo" touching="black"></div>
<div class="demo" touching="orange"></div>
<div class="demo" touching="top"></div>
<div class="demo" touching="green"></div>
<div class="demo" touching="black"></div>
<div class="demo" touching="orange"></div>
<div class="demo" touching="top"></div>
<div class="demo" touching="green"></div>
<div class="demo" touching="black"></div>
<div class="demo" touching="orange"></div>
<div class="demo" touching="top"></div>
<div class="demo" touching="green"></div>
<div class="demo" touching="black"></div>
<div class="demo" touching="orange"></div>
<div class="demo" touching="top"></div>
<div class="demo" touching="green"></div>
<div class="demo" touching="black"></div>
<div class="demo" touching="orange"></div>