描述:两侧的对联广告,在页面最终的位置保持不变,会随着页面的滚动,而缓慢移动到最终的位置。小编是用图片进行的占位,引用的话可以把图片换成其他内容。
示例代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>两侧跟随广告</title>
    <style>
        .img1 {
            position: absolute;
            top: 80px;
            left: 10px;
        }
        .img2 {
            position: absolute;
            top: 80px;
            right: 10px;
        }
        div {
            width: 1210px;
            height: 2000px;
            margin: 100px auto;
            text-align: center;
            font: 500 26px/35px "simsun";
        }
    </style>
    <script>
        window.onload = function () {
            //获取相关元素,获取的是两侧的对联广告
            var imgArr = document.getElementsByTagName("img");
            //鼠标滑动事件
            window.onscroll = function () {
                var val = scroll().top;
                for (var i = 0;i<imgArr.length;i++){
                    animate(imgArr[i],val+80);
                }
            }
        }

        /**
         * 封装的动画
         * @param 调用者
         * @param 目标位置
         */
        function animate(ele,target) {
            clearInterval(ele.timer);
            ele.timer = setInterval(function () {
                var step = (target-ele.offsetTop)/10;
                step = step>0?Math.ceil(step):Math.floor(step);
                ele.style.top = ele.offsetTop + step + "px";
                if(Math.abs(target-ele.offsetTop)<Math.abs(step)){
                    ele.style.top = target + "px";
                    clearInterval(ele.timer);
                }
            },25);
        }
        function scroll(){
            return {
                "top": window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop,
                "left":  window.pageXOffset || document.body.scrollLeft || document.documentElement.scrollLeft
            }
        }
    </script>
</head>
<body>
    <img class="img1" src="images/aside.jpg" height="469" width="132"/>
    <img class="img2" src="images/aside.jpg" height="469" width="132"/>
    <div></div>
</body>
</html>
Last modification:April 16, 2018
If you think my article is useful to you, please feel free to appreciate