zoukankan      html  css  js  c++  java
  • javascript跟随滚动条滚动,onscroll事件的学习

      今天研究了一下,滚动条事件,也是在无忧上看到的,顺便做下记录@

    比如做一个浮动广告效果,原理就是 设置一个定时器0.1秒检测层所在的位置  并将他指定到 相当于窗口的位置.

    核心代码如下:

    代码
    <script type="text/javascript">
    function scrollImg(){
    var posX,posY;
    if (window.innerHeight) { //兼容判断
    posX
    = window.pageXOffset;
    posY
    = window.pageYOffset;
    }
    else if (document.documentElement && document.documentElement.scrollTop) { //兼容判断

    posX
    = document.documentElement.scrollLeft;
    posY
    = document.documentElement.scrollTop;
    }
    else if (document.body) { //兼容判断

    posX
    = document.body.scrollLeft;
    posY
    = document.body.scrollTop;
    }

    var ad=document.getElementById("ad");
    ad.style.top
    =(posY+100)+"px";
    ad.style.left
    =(posX+50)+"px";
    setTimeout(
    "scrollImg()",100);
    }
    </script>

    重点,也是常犯错误的地方:

    在xhtml页面中,document.body.scrollTop始终为0,即该属性无效,因此必须用其他的属性来判断,为兼容新旧标准,应该对属性的可用性进行判断。

     

    应用WEB标准会使ScrollTop属性失效!!! 
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0  Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
    <html xmlns="http://www.w3.org/1999/xhtml"> 
    
    加上这段后,document.body.scrollTop永远等于0 
    
    
    body onscroll = "alert(document.body.scrollTop);"永远也不会引发。  
    
    

     

    解决办法:使用:

    document.documentElement.scrollTop

    下面有2个例子

    示例一: 
    
    var scrollPos; 
    if (typeof window.pageYOffset != 'undefined') {  //netscape 
    scrollPos = window.pageYOffset; 
    } 
    
    else if (typeof document.compatMode != 'undefined' && 
    document.compatMode != 'BackCompat') { 
    scrollPos = document.documentElement.scrollTop; 
    } 
    
    else if (typeof document.body != 'undefined') { 
    scrollPos = document.body.scrollTop; 
    } 
    
    alert(scrollPos); 
    
    
    示例二: 
    
    function WebForm_GetScrollX() 
    { 
    if (__nonMSDOMBrowser) 
    { 
    return window.pageXOffset; 
    } 
    else 
    { 
         if (document.documentElement && document.documentElement.scrollLeft) 
         { 
              return document.documentElement.scrollLeft; 
          } 
        else if (document.body) 
        { 
           return document.body.scrollLeft; 
        } 
    } 
        return 0; 
    } 
    
    @@@@@@
    pageYOffset是netscape的 
    document.body.scrollTop和document.documentElement.scrollTop是ie的,但我不知道他们的真正区别,
    只知道documentElement.scrollTop是xhtml兼容的(作者用的是strict) 
    
    

     

     

  • 相关阅读:
    通过网格拆分高德地图
    vue-router重定向 不刷新问题
    vue-scroller记录滚动位置
    鼠标滚轮更改transform的值(vue-scroller在PC端的上下滑动)
    position sticky的兼容
    js截图及绕过服务器图片保存至本地(html2canvas)
    禁止页面回退到某个页面(如避免登录成功的用户返回到登录页)
    手动创建script解决跨域问题(jsonp从入门到放弃)
    逻辑回归的常见面试点总结
    听说你不会调参?TextCNN的优化经验Tricks汇总
  • 原文地址:https://www.cnblogs.com/NetSos/p/1875577.html
Copyright © 2011-2022 走看看