js实现图片上下滚动background-position

    科技2022-08-17  124

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript" src="js/jquery-3.2.1.min.js"></script> <style> * { margin: 0; } .a{ background: pink; width: 100%; height: 1000px; } .b{ background: url("images/未标题-1.jpg") no-repeat; background-position: 0px 0px; width: 100%; height: 420px; background-attachment: fixed; background-size: 100%; } .c{ background: #FF5B77; width: 100%; height: 500px; } </style> </head> <body> <div class="a"></div> <div class="b"> </div> <div class="c"></div> </body> <script> (function(){ var b = document.getElementsByClassName("b")[0]; //获取顶点到b的高度 var bof = b.offsetTop;//1000 window.onscroll = function(){ //获取滚动的高度 var scHeight = document.documentElement.scrollTop; console.log(bof - scHeight); b.style.backgroundPositionY = (bof - scHeight)*0.5 +"px"; } })(); </script> </html>
    Processed: 0.009, SQL: 9