1. 程式人生 > >js的window.onscroll事件兼容各大瀏覽器

js的window.onscroll事件兼容各大瀏覽器

public spa pan 標題 cnblogs window set 滾動條事件 Language

為窗口添加滾動條事件其實非常的簡單,
window.onscroll=function(){};
註意在獲取滾動條距離的時候
谷歌不識別document.documentElement.scrollTop,必須要加上document.body.scrollTop;即
var scrolltop=document.documentElement.scrollTop||document.body.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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>無標題文檔</title> <style type="text/css"> #box{ height:50px; width:200px; background:#666; position:absolute; left:0px; top:0px;} </style> </
head> <body style="height:9000px;"> <div id="box"></div> <script language="javascript"> window.onscroll = function(e){ var e =e || window.event; var scrolltop=document.documentElement.scrollTop||document.body.scrollTop; var box = document.getElementById(box); box.style.top
= scrolltop+px; //console.log(scrolltop); } </script> </body> </html>

js的window.onscroll事件兼容各大瀏覽器