我正在尝试更改滚动元素的透明度:
当一个元素出现时,在它滚动时将其不透明度从 0 更改为 1
当元素开始“离开”范围时,在滚动时将其透明度从 1 更改为 0
function changeOpacity(){
var windowScrollTop = $(window).scrollTop(),
docHeight = $(document).height(),
windowHeight = $(window).height(),
elOffset = $('.shab1').offset().top,
elHeight = $('.shab1').outerHeight(),
opacity = 1 - (windowScrollTop - elOffset + elHeight) / elHeight,
opacity2 = 1 + (windowScrollTop - elOffset + elHeight) / elHeight;
if(opacity > 1) opacity = 1;
if(opacity2 > 1) opacity2 = 1;
if(opacity <= 0) opacity = 0;
if(opacity2 <= 0) opacity2 = 0;
if(windowScrollTop + windowHeight > (elOffset - elHeight) / elHeight){
$('.shab1').css('opacity', opacity);
}
}
changeOpacity();
$(window).on('scroll', function(){
changeOpacity();
});
body{min-height:3000px;background:#000}
.shab1{background:red;text-align: center;padding:60px 0;opacity:0;}
.elem{width:100%;height:40px;text-align:center;font-size:30px;margin:0 0 90%;}
.elem1{background:green}
.elem2{background:blue}
.elem3{background:purple}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div class="elem elem1">не тот блок</div>
<div class="elem elem2">не тот блок</div>
<h1 class="elem shab1">Stackoverflow, помоги, пожалуйста</h1>
<div class="elem elem3">не тот блок</div>
</body>
</html>