视觉差网页的实现原理

利用background-attachment: fixed; 配合js设置background-position来实现。

具体的代码如下:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    body,
    html {
      margin: 0;
      width: 100%;
      height: 100%;
    }

    #bg1 {
      width: 100%;
      height: 100%;
      background-color: antiquewhite;
      background-image: url(https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1594814547574&di=89f3c69ea703d15beb12d52c3dc07388&imgtype=0&src=http%3A%2F%2Fimg.pconline.com.cn%2Fimages%2Fupload%2Fupc%2Ftx%2Fwallpaper%2F1304%2F17%2Fc5%2F19955421_1366189671581.jpg);
      background-repeat: no-repeat;
      background-size: 100% 100%;
      background-attachment: fixed;
    }

    #bg2 {
      width: 100%;
      height: 100%;
      background-color: antiquewhite;
      background-image: url(https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1594814547573&di=70f7d70fcf76e8032761f32425b64735&imgtype=0&src=http%3A%2F%2Fimg.pconline.com.cn%2Fimages%2Fupload%2Fupc%2Ftx%2Fwallpaper%2F1308%2F15%2Fc5%2F24496183_1376533418348.jpg);
      background-size: 100% 120%;
      background-repeat: no-repeat;
      background-attachment: fixed;
    }

    #bg3 {
      width: 100%;
      height: 100%;
      background-color: antiquewhite;
      background-image: url(https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1594814547573&di=c5ea816e268c2a5e857dc395b4c23b05&imgtype=0&src=http%3A%2F%2Fattach.bbs.miui.com%2Fforum%2F201401%2F23%2F095609lsejfi4thjrrwydj.jpg);
      background-size: 100% 140%;
      background-repeat: no-repeat;
      background-attachment: fixed;
    }
  </style>
</head>

<body>
  <div id="bg1"></div>
  <div id="bg2"></div>
  <div id="bg3"></div>
  <script>
    const bg1 = document.querySelector('#bg1');
    const bg2 = document.querySelector('#bg2');
    const bg3 = document.querySelector('#bg3');
    window.addEventListener("scroll", function () {
      const t = document.documentElement.scrollTop / 10;
      bg1.style.backgroundPositionY = -t + 'px';
      bg1.style.transform = "translateY(" + (-t) + "px)";
      bg2.style.backgroundPositionY = -t + 'px';
      bg2.style.transform = "translateY(" + (-t) + "px)";
      bg3.style.backgroundPositionY = -t + 'px';
      bg3.style.transform = "translateY(" + (-t) + "px)";
    });
    
  </script>
</body>

</html>

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值