中间or底部浮动(用到Math)

类似广告的中间或底部浮空模块
中间浮动时计算target
scrollTop:当前区域顶部距离body顶部距离,注意兼容(详见代码);
cilentHeight:可视区域高度;
half:(clientHeight-odiv.offsetHeight)/2;
target:scrollTop+half;

      <style type="text/css">
        *{margin:0; padding:0;}
        body{height:2000px; }
        #div1{width:100px; height:100px; background:red; 
          position:absolute; right:0; }
    </style>
 <body>
   <div id="div1"> </div>
 </body>
 <script type="text/javascript">
 <!--
    var odiv1=document.getElementById("div1");
    var timer;
    var speed;

    window.onscroll=function(){
        console.log("..........................."); 
//  注意兼容  
      var scrollTop=document.documentElement.scrollTop || document.body.scrollTop;
//    console.log("scrollTop  "+scrollTop);

//    clientHeight 可视区域高度 当滚动条在最底部 可视高度+scrollTop=body高度
      var hview=document.documentElement.clientHeight;
//    half  (可视部分高度-odiv高度)/2  避免小数用parseInt() 转换
      var half=parseInt((hview-odiv1.offsetHeight)/2);    
//    console.log("可视高度  "+document.documentElement.clientHeight);

//    move(scrollTop+half);  // 中间浮动
      move(scrollTop+hview-odiv1.offsetHeight); // 底部浮动


//    下行代码为中间浮动的 target(即odiv1.style.top的位置)
//    scrollTop+half

//    下行代码为底部浮动的 target(即odiv1.style.top的位置)
//    scrollTop+hview-odiv1.offsetHeight    
    } // scroll

    var timer=null;
    var speed=0;
    function move(target){
      clearInterval(timer); //清空定时器
      timer=setInterval(function(){
        if(odiv1.offsetTop==target){
          clearInterval(timer);//到达target停止定时器
        }else{
//  计算缓冲运动速度,注意一定要判定±然后向上/向下取整      
          speed=(target-odiv1.offsetTop)/3;
          speed=speed>0?Math.ceil(speed):Math.floor(speed);
          odiv1.style.top=odiv1.offsetTop+speed+"px";
          console.log("速度"+speed);
        }

      },30); //定时器结束
    } // move
 //-->   
 </script>

常用Math函数:
随机数:Math()*n ,取0~n的随机小数,如果取整可用parseInt( )转换;
向上取整:Math.ceil(float), -0.1→0 / 0.1→1;
向下取整:Math.floor(float),-0.1→-1 / 0.1→0;
绝对值:Math.abs(num);
四舍五入取整:Math.round(num);

获取可视区域高度:兼容方式
var scroll=Topdocument.documentElement.scrollTop ||
document.body.scrollTop;

注:div的position定位需注意,当前情况必须是positon:absolute;
缓冲运动speed速度一定要处理取整,±时判断上/下取整(可用三元判断)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值