实现滚动窗口触发动画需要js的帮助。有jquery的一个全屏滚动插件fullpage.js
fullPage.js是开源的JQuery插件库,其Github地址:https://github.com/alvarotrigo/fullPage.js
fullPage.js 是一个基于 jQuery 的插件,它能够很方便、很轻松的制作出全屏网站,主要功能有:
当然也可以自己实现。
下面是一个实现参考:
HTML代码:
<header>
<h1>Animation on Scroll</h1>
</header>
<main class="page-wrapper">
<section class="section">
<h2>SECTION</h2>
<div class="section-content">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ad animi at, atque commodi cupiditate
doloremque eius exercitationem, maiores modi obcaecati officia quod, recusandae sed sequi sit soluta sunt vitae! Temporibus.</p>
<img src="https://images.unsplash.com/photo-1463123081488-789f998ac9c4?format=auto&auto=compress&dpr=1&crop=entropy&fit=crop&w=1199&h=799&q=80" alt="picture">
</div>
</section>
</main>
CSS代码:
@mixin prefix($property, $value) {
@each $prefix in -webkit-, -moz-, -ms-, -o-, '' {
#{$prefix}#{$property}: $value;
}
}
%transition{
@include prefix(transition, all 2s ease-out);
}
body {
background-color: #48cfad;
color: #fff;
overflow-x: hidden;
}
header {
height: 100vh;
text-align: center;
line-height: 100vh;
}
.page-wrapper {
width: 80%;
margin: 50px auto;
box-sizing: border-box;
@media (max-width: 767px) {
width: 100%;
margin: 20px 0;
padding: 0 15px;
}
}
.section {
// 动画效果前
width: 100%;
height: 100vh;
padding: 40px 0;
opacity: 0;
@include prefix(transform, translateY(50px));
@extend %transition;
h2 {
font-size: 30px;
text-align: center;
}
.section-content {
width: 80%;
margin: 0 auto;
text-align: center;
@media (max-width: 767px) {
width: 100%;
}
p {
max-width: 80%;
margin: 20px auto 50px;
@include prefix(transform, translateX(-100px));
@extend %transition;
}
img {
width: 100%;
border-radius: 4px;
@include prefix(transform, translateX(100px));
@extend %transition;
}
}
&.animation {
// 动画效果后
opacity: 1;
@include prefix(transform, translateY(0));
.section-content {
p,
img{
@include prefix(transform, translateX(0));
}
}
}
}
JS代码
/* by www.geekwen.com */
function revealOnScroll() {
var scrolled = $(window).scrollTop();
// 视窗,即viewport,页面可视范围的窗口
$(".section").each(function() {
var current = $(this), // 当前元素
w_height = $(window).outerHeight(), //视窗高度
offsetTop = current.offset().top; //当前元素离顶部的高度
// 计算高度差(此处预留50是为了看效果)
// 当元素进入视窗时,添加class
if (scrolled + w_height - 50 > offsetTop) {
current.addClass("animation");
} else {
current.removeClass("animation");
}
});
}
$(window).on("scroll", revealOnScroll);
最后大体效果可以参考
https://codepen.io/geekwen/pen/oXpjZN