JS广告特效

效果图

在这里插入图片描述
添加了一个解决兼容性问题的求滚动长度距离的函数

/**
 * 获取滚动的头部距离和左边距离
 * scroll().top scroll().left
 * @returns {{top: number, left: number}}
 */
function scroll() {
    if(window.pageXOffset!==null)//新型模式
    {
        return {
            top:window.pageYOffset,
            left:window.pageXOffset
        }
    }else if(document.compatMode==="CSS1Compat"){//严格模式
        return{
            top:document.documentElement.scrollTop,
            left:document.documentElement.scrollLeft,
        }
    }
    return{//异常模式
        top:document.body.scrollTop,
        left:document.body.scrollLeft,
    }
}

HTML

<div id="side">
  <img src="图片/6.jpg" alt="">
</div>

还有一坨的p为了弄长点好滚动

css

*{
      margin: 0;
      padding: 0;
      list-style: none;
      border: none;
    }
    #side{
      width: 150px;
      height: 200px;
      position: absolute; 默认对body定位
      left: 0;
      top: 150px;
    }
    #side img{
      width: 100%;
      height: 100%;
    }
    p{
      height: 50px;
      text-align: center;
      font-size: 20px;
    }

JS

分析

网页滚动(onscroll)时,侧边广告会缓动(缓动动画)滑到最初的位置
缓动动画:缓动系数、定时器
定时器:先清除后设置、在达到要求之后,及时清除定时器

<script>
function $(id) {
  return document.getElementById(id);
}
  window.onload = function () {
    console.log($("side"));
    var Offsettop=$("side").offsetTop;//获取侧边广告距离顶部的距离
    //2、窗口滚动
    var begin=0,end=0,timer=null;
    window.onscroll = function () {
      //2、0在时间开始的地方清除
      clearInterval(timer);
      //2、1获取滚动高度
      var scrollTop=scroll().top;
      Ed=offsettop+scrollTop;
      //结束位置为:滚动的长度和当前距离页面顶部的长度
      timer=setInterval(function () {
            begin=begin+(Ed-begin)*0.2;
            //根据公式,设置起止值
            $("side").style.top=begin+"px";
            //begin
        if(Math.round(begin)===end){
          //定时器使用了要清除
         clearInterval(timer);
        }
      },20);
    }
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值