我正在尝试实现类似于Apple News的效果,其中照片在滚动时淡入,但是一旦达到100%的不透明度,它就不会淡出。This video demonstrates the fade in:但是,它不会证明它完全消失了。
我已经开始使用淡入效果,但是我不确定如何将不透明度保持在100%。我在下面添加了一些模拟代码,尽管出于某种原因,它似乎无法在stackoverflow上正确执行? It does work on codepen though
function fadeIn() {
$(document).scroll(function(){
var scrollPos = $(this).scrollTop();
var parallaxTop = $('#fade1').offset().top;
var parallaxStart = parallaxTop * .1;
var opacity1 = (scrollPos - parallaxStart);
if ($(this).scrollTop() >= parallaxStart) {
$('#fade1').css('opacity' , 0 + opacity1);
}
})
}
fadeIn();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<head>
</head>
<body>
<div style="display: block; width:300px;">
<h1>Take Charge</h1>
<h4>Transform your body with a personal trainer in 2019</h4>
</div>
<p>hello</p><br>
<p>hello</p><br>
<p>hello</p><br>
<p>hello</p><br>
<p>hello</p><br>
<p>hello</p><br>
<p>hello</p><br>
<p>hello</p><br>
<p>hello</p><br>
<p>hello</p><br>
<p>hello</p><br>
<p>hello</p><br>
<div id="fade1" style="display: block; width:300px;">
<h1>Take Charge</h1>
<h4>Transform your body with a personal trainer in 2019</h4>
<p>hello</p><br>
<p>hello</p><br>
<p>hello</p><br>
<p>hello</p><br>
<p>hello</p><br>
<p>hello</p><br>
<p>hello</p><br><p>hello</p><br>
<p>hello</p><br>
<p>hello</p><br>
<p>hello</p><br>
<p>hello</p><br>
</body>
答案 0 :(得分:1)
有两种方法可以实现所需的内容,并防止元素淡入淡出。
如果不透明度已经是1.0,则您不想更改它,因此如果检测到不透明度,可以从滚动回调中提早返回。
$(document).scroll(function(){
// NOTE: Check the opacity and don't change it if the element has
// already faded in completely
if($('#fade1').css('opacity') === 1) return;
var scrollPos = $(this).scrollTop();
var parallaxTop = $('#fade1').offset().top;
var parallaxStart = parallaxTop * .1;
var opacity1 = (scrollPos - parallaxStart)/600;
if ($(this).scrollTop() >= parallaxStart) {
$('#fade1').css('opacity' , 0 + opacity1);
}
});
或
如果预计该元素将永远不会消失,则只需删除
function scrollCallback(){
var scrollPos = $(this).scrollTop();
var parallaxTop = $('#fade1').offset().top;
var parallaxStart = parallaxTop * .1;
var opacity1 = (scrollPos - parallaxStart)/600;
if ($(this).scrollTop() >= parallaxStart) {
$('#fade1').css('opacity' , 0 + opacity1);
// NOTE: If we've faded in completely then we don't need the event anymore
if (opacity1 >= 1.0) {
$(document).unbind('scroll', scrollCallback);
}
}
};
$(document).bind('scroll', scrollCallback);
希望这些选项之一对您有用!