javascript跟随滚动条滚动的层(浮动AD效果)
其实这个效果在很多网站中都能见到,其主要表现为网页两侧的浮动广告。看起来感觉很难做,但其实原理是很简单的,使用定时器没0.1秒检测层的位置并将其置在指定的位置(相对于窗口)。写了一个简单的代码:
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);
}
此广告位招租
scrollImg();
[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]
注意: 
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; 
   } 
这段代码是为了兼容标准,在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
示例一:
var scrollPos;  
if (typeof window.pageYOffset != 'undefined') {  
  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)
