我在各节中有opacity: 0
个元素。并尝试使opacity: 1
的部分在窗口中完全可见。我写的代码如下。它有缺陷。
$(window).scroll( function(){
$('.parts').each(function(i){
var sectionBottom = $(this).position().top + $(this).outerHeight();
var windowBottom = $(window).scrollTop() + $(window).height();
if( windowBottom > (sectionBottom + 300) ){
$("h1").css("opacity", "1");
$("h2").css("opacity", "1");
$("h3").css("opacity", "1");
}
});
});
.parts {
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.part1 {
background-color: yellow;
}
.part2 {
background-color: red;
}
.part3 {
background-color: blue;
}
h1,h2,h3 {
text-align: center;
color: #000;
opacity: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="parts part1">
<h1>this is the el of 1</h1>
</section>
<section class="parts part2">
<h2>this is the el of 1</h2>
</section>
<section class="parts part3">
<h3>this is the el of 1</h3>
</section>
它一次显示所有元素。如何使元素仅显示其在窗口中可见的部分。
答案 0 :(得分:1)
滚动功能中有一个小问题。滚动功能只是检查node_modules\.bin\ng-packagr
,如果它是真的,那么它也会使其他部分可见。
要解决此滚动问题,请检查该部分是否在窗口中可见,然后使元素在其中可见(windowBottom > (sectionBottom + 300)
)。
opacity: 1
答案 1 :(得分:1)
sectionDisplay();
$(window).scroll(function() {
sectionDisplay();
});
function sectionDisplay() {
$('.parts').each(function(i) {
if ($(this).position().top - 100 <= $(window).scrollTop()) {
$(this).children().animate({
opacity: 1
});
}
});
}
.parts {
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.part1 {
background-color: yellow;
}
.part2 {
background-color: red;
}
.part3 {
background-color: blue;
}
h1,
h2,
h3 {
text-align: center;
color: #000;
opacity: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="parts part1">
<h1>this is the el of 1</h1>
</section>
<section class="parts part2">
<h2>this is the el of 1</h2>
</section>
<section class="parts part3">
<h3>this is the el of 1</h3>
</section>
<section class="parts part1">
<h1>this is the el of 1</h1>
</section>
<section class="parts part2">
<h2>this is the el of 1</h2>
</section>