我想用 jQuery 和 CSS 做一个简单的视差效果。
我有 2 个长 div,一个是 2000px
,另一个是 1000px
每个 div 都有一个子 div,里面有文字。
我想让这些子 div 位于可见窗口的中间(不是 2000px
高的 div,只是可见窗口)并保持居中和中间当我向下滚动时,然后在到达下一个 div 之前的某个点淡出。
目前,我设法创建了 html 布局和 css,并使用 jQuery 使 div 在点击时淡出。
但是当我向下滚动并在到达下一个 div 之前淡出它们时,我无法将它们居中放置在窗口中间并保持它们固定。
也许我可以使用 Waypoint.js 在滚动中的某些点触发事件,但如何使 div 居中并可见以实现视差效果?
演示 https://jsfiddle.net/fmub10pv/4/
编辑 是否有任何插件(带演示)可以实现我想要的?
EDIT 2 想要的效果是这样的 http://davegamache.com/parallax/
HTML
<div class="container" id="firstContainer">
<div class="row">
<div class="col-md-12 text-center">
<div id="firstDiv" class="animate text-center">
<h1>First Div</h1>
</div>
</div>
</div>
</div>
<div class="container" id="secondContainer">
<div class="row">
<div class="col-md-12 text-center">
<div id="secondDiv" class="animate text-center">
<h1>Second Div</h1>
</div>
</div>
</div>
</div>
CSS
body {
background-color: #16191b;
color: white;
}
#firstContainer {
height: 2000px;
margin-top: 80px;
background: darkslategrey;
}
#secondContainer {
height: 1000px;
background: darkslateblue;
}
.animate {
padding: 20px;
background: mediumseagreen;
}
#firstDiv {
opacity: 1;
-webkit-transition: all 0.5s ease-in-out;
-moz-transition: all 0.5s ease-in-out;
-ms-transition: all 0.5s ease-in-out;
-o-transition: all 0.5s ease-in-out;
transition: all 0.5s ease-in-out;
}
#secondDiv {
opacity: 1;
-webkit-transition: all 0.5s ease-in-out;
-moz-transition: all 0.5s ease-in-out;
-ms-transition: all 0.5s ease-in-out;
-o-transition: all 0.5s ease-in-out;
transition: all 0.5s ease-in-out;
}
Javascript
$(document).ready(function() {
var current = $(window).scrollTop();
var winHeight = $(window).height();
var total = winHeight - current;
$('#firstDiv').on('click', function() {
if ($('#firstDiv').css('opacity') == 0) $('#firstDiv').css('opacity', 1);
else $('#firstDiv').css('opacity', 0);
});
$('#secondDiv').on('click', function() {
if ($('#secondDiv').css('opacity') == 0) $('#secondDiv').css('opacity', 1);
else $('#secondDiv').css('opacity', 0);
});
});
最佳答案
以下将检查您是否通过了某个航路点,并根据您之后滚动的距离更新不透明度。
你介意 jQuery 吗?
$(window).scroll(function() {
waypoint = 400
if ($(document).scrollTop() > waypoint) {
alpha = 1 - (($(document).scrollTop() - waypoint) / 260) // 260 is an arbitrary number, the size determines how quickly it will fade out (reach 0)
} else {
alpha = 1
}
$("#fade").css({
"opacity": alpha
});
});
关于javascript - 保持 div 在窗口中间可见,同时向下滚动并在到达某个点后淡出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43057590/