我设法让div(s)在滚动时保持顶部偏移64px但我也希望相同div的不透明度渐变为0.我无法弄清楚如何添加这个?我到目前为止所做的一个例子。
$(window).scroll(function(){
var scrollTop = $(this).scrollTop();
$(".ComponentOne").css("top",Math.max(64,800-scrollTop));
});
答案 0 :(得分:1)
<强>更新强>
尝试以下代码:
<强>的jQuery 强>
$(window).scroll(function() {
var scrollTop = $(this).scrollTop();
var offsetTop = $('.ComponentOne').position().top;
console.log(offsetTop);
$(".ComponentOne").css("top", Math.max(64, 800 - scrollTop));
if (offsetTop === 64) {
$(".ComponentOne").css("opacity", "0");
} else {
$(".ComponentOne").css("opacity", "1");
}
});
<强> CSS 强>
.ComponentOne {
transition: opacity 500ms ease;
height: 100px;
background: #000;
position: fixed;
left: 0;
right: 0;
}
答案 1 :(得分:0)
CSS
.ComponentOne{
height:100px;
width:200px;
background:pink;
position:absolute;
top:800px;
opacity:0;
}
JS
$("document").ready(function(){
$(window).scroll(function(){
var scrollTop = $(this).scrollTop();
var compTop = $('.ComponentOne').offset().top;
var controllOpacity = 1400;
if(scrollTop + 100 > compTop)
{
$(".ComponentOne").css("top","64px");
$(".ComponentOne").css("position","fixed");
$(".ComponentOne").css("opacity", ((scrollTop - 800)/(controllOpacity - 800)));
}
if(scrollTop < 800){
$(".ComponentOne").css("top","800px");
$(".ComponentOne").css("position","absolute");
$(".ComponentOne").css("opacity", ((scrollTop - 800)/(controllOpacity - 800)));
}
});
});
只需根据您调整controlOpacity变量的值即可。它用于控制div应该完全淡出的范围。因此,如果你降低它,div会在你晃动时迅速淡出,如果你保持它大,那么div会慢慢淡出滚动
JSFiddle示例