js背景跟随

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body{
            background-color: #04090C;
        }
        div{
            height: 45vh;
            margin-bottom: 5vh;
            background-position: 40%;
            background-repeat: no-repeat;
        }
        .bg_1{
            background-image: url("bg.png");
        }
        .bg_2{
            background-image: url("bg2.png");
            background-position-x: 70%;
        }
    </style>
</head>
<body>
<div class="bg_1"></div>
<div class="bg_2"></div>

<script>
    let ele1 = document.querySelector(".bg_1");
    let ele2 = document.querySelector(".bg_2");
    let winWidth = window.innerWidth
    window.addEventListener("mousemove",function (ev) {
        let percent =  ev.clientX/winWidth;
        let fruit1 = 40*(1-percent);
        let fruit2 = 70*(1-percent);
        ele1.style.backgroundPositionX =  fruit1 +"%";
        ele2.style.backgroundPositionX =  fruit2 +"%";
    })
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_40285497/article/details/80570840
今日推荐