使用简单的前端完成内视差效果
效果图如下:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/f020738f03a63d9edd3c424e78825ff7.gif#pic_center)
本案例使用html+sass+jQuery,很简单哒!
HTML代码:
<section class="section-1">
<div class="section-top">
// 选择你要插入的图片,一定要确保路径正确
<div class="img parallax"
style="background-image: url(./images/image-2.jpg);">
</div>
</div>
<div class="section-bottom">
// 略...自己要啥写啥
</div>
</section>
sass代码:
.section-1 {
display: flex;
flex-direction: column;
.section-top {
width: 100%;
.img {
background-repeat: no-repeat;
background-position: center;
background-size: cover;
width: 100%;
padding-top: 38.21%;
}
}
.section-bottom {
}
}
jQuery代码:
function parallax() {
if (jQuery(window).width() >= 768) {
var wh = jQuery(window).height();
var sh = jQuery(window).scrollTop();
jQuery(".parallax").each(function () {
var parallax_h = jQuery(this).offset().top;
var item_h = jQuery(this).outerHeight();
var parallax_y;
if (sh > (parallax_h - wh) && sh < parallax_h + item_h) {
parallax_y = 100 * (sh - (parallax_h - wh)) / (wh + item_h);
} else if (sh > parallax_h + item_h) {
parallax_y = 0;
}
jQuery(this).css('background-position', 'center bottom ' + parallax_y + '%');
});
} else {
jQuery('.parallax').css('background-position', 'center top 0');
}
}
完成!