javascript跟隨捲軸滾動,onscroll事件的學習

來源:互聯網
上載者:User

  今天研究了一下,捲軸事件,也是在無憂上看到的,順便做下記錄@

比如做一個浮動廣告效果,原理就是 設定一個定時器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) 

 

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.