【前端】使用jQuery完成简单的内视差效果、内视差效果

使用简单的前端完成内视差效果

效果图如下:

在这里插入图片描述

本案例使用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() {
    // 此处写的范围是屏宽大于等于768px的时候特效才生效
    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添加你需要滚动的高度
            jQuery(this).css('background-position', 'center bottom ' + parallax_y + '%');
        });
    } else {
        // 如果屏宽小于768px的时候就不生效了
        jQuery('.parallax').css('background-position', 'center top 0');
    }
}

完成!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值