【前端】这个网页中背景轮换的效果是如何实现的?
https://templated.co/roadtrip
这个网页中当上下滚动时,背景会跟着变换,这是如何实现的。
回答
提供个思路,js得到滚动的值,然后给元素的background-position做改变,代码在下面,可以试一下。图片的路径要注意
css
    <style>        html, body {height:100%;overflow:auto;margin: 0;}
        .wrap{
            width: 900px;
            height: 450px;
            overflow-x: hidden;
            overflow-y: scroll;
            position: relative;
        }
        .one,.two,.three{
            width: 900px;
            height: 450px;
        }
        .one{
            background-color: rgba(0, 255, 0, 0.2)
        }
        .two{
            background-color: rgba(255, 0, 0, 0.2)
        }
        .three{
            background-color: rgba(0, 0, 255, 0.2)
        }
        .bgImgOne{
            width: 900px;
            height: 450px;
            position: absolute;
            z-index: -1;
            top: 0;
            background: url("./img/1.jpeg") no-repeat top left / 900px 450px;
        }
        .bgImgTwo{
            width: 900px;
            height: 450px;
            position: absolute;
            z-index: -1;
            top: 450px;
            background: url("./img/2.jpeg") no-repeat top left / 900px 450px;
        }
        .bgImgThree{
            width: 900px;
            height: 450px;
            position: absolute;
            z-index: -1;
            top: 900px;
            background: url("./img/2.jpg") no-repeat top left / 900px 450px;
        }
    </style>
html
        <div class="wrap">            <div class="bgImgOne"></div>
            <div class="bgImgTwo"></div>
            <div class="bgImgThree"></div>            
            <div class="one">111111111</div>
            <div class="two">222222222</div>
            <div class="three">333333333</div>
        </div>
js
            var wrap = document.getElementsByClassName('wrap')[0];            var bgImgOne = document.getElementsByClassName('bgImgOne')[0];
            var bgImgTwo = document.getElementsByClassName('bgImgTwo')[0];
            var bgImgThree = document.getElementsByClassName('bgImgThree')[0];
            var num = 0;
            wrap.addEventListener("scroll", function() {
                num = wrap.scrollTop;
                bgImgOne.style.backgroundPosition = "0px " + num + "px";
                bgImgTwo.style.backgroundPosition = "0px " + (num-450) +"px";
                if(num>=450){
                    bgImgThree.style.backgroundPosition = "0px " + (num-900) +"px";
                }
            })



background-position
以上是 【前端】这个网页中背景轮换的效果是如何实现的? 的全部内容, 来源链接: utcz.com/a/81066.html

