符合标准的对联广告

原始代码:
lastScrollY=0;
function heartBeat(){
diffY=document.body.scrollTop;
percent=.1*(diffY-lastScrollY);
if(percent>0)percent=Math.ceil(percent);
else percent=Math.floor(percent);
document.getElementById("lovexin12").style.top=parseInt(document.getElementById("lovexin12").style.top)+percent+"px";
document.getElementById("lovexin14").style.top=parseInt(document.getElementById("lovexin12").style.top)+percent+"px";
lastScrollY=lastScrollY+percent;
}
suspendcode12="<DIV id=\"lovexin12\" style='left:2px;POSITION:absolute;TOP:120px;'>ad1</div>"
suspendcode14="<DIV id=\"lovexin14\" style='right:2px;POSITION:absolute;TOP:120px;'>ad2</div>"
document.write(suspendcode12);
document.write(suspendcode14);
window.setInterval("heartBeat()",1);

这个在以前是可以正常运行的,只要你不使用文档类型声明。

但是,标准设计的网页需要进行文档类型声明以告知浏览器按照怎样的规则去解析网页。当我们使用过渡型标准声明的时候,我们发现这个原本工作正常的对联代码不再起作用。

这是符合标准的代码,和上面的区别是它加了文档类型声明:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


为什么小小的标准声明让对联广告无法工作?

问题的根源:
google了几篇文章之后,找到了真凶!哦,抱歉,没有这么夸张了。
让我们回到第一段代码:
注意这一句:diffY=document.body.scrollTop;
当我们采用标准声明之后,你会发现无论你怎样拖动滚动条,diffY的值始终为零。见鬼了吗?不,事实上从html4/loose.dtd开始,只要你采用了相应的文档类型声明,diffY的值就会恒为零(有一种特殊情况,下面谈)。
为什么会这样?
因为采用标准的文档类型声明后,document.body.scrollTop已经无效,而应该用document.documentElement.scrollTop代替。
不仅仅是scrollTop有这种改变,更多请参加表(一)。
在表(一)中有这样一行:“Note: scrollLeft and scrollTop also work on DIV's with overflow: auto in Explorer 5+ on Windows and Mozilla 1.1”,这就是我所说的特殊情况。

怎么解决?
将第一段代码做一些修改:
var diffY;
if (document.documentElement && document.documentElement.scrollTop)
  diffY = document.documentElement.scrollTop;
else if (document.body)
  diffY = document.body.scrollTop
else
{/*Netscape stuff*/}

这个是完整版本:
// JavaScript Document
lastScrollY=0;
function heartBeat(){
var diffY;
if (document.documentElement && document.documentElement.scrollTop)
  diffY = document.documentElement.scrollTop;
else if (document.body)
  diffY = document.body.scrollTop
else
{/*Netscape stuff*/}
  
//alert(diffY);
percent=.1*(diffY-lastScrollY);
if(percent>0)percent=Math.ceil(percent);
else percent=Math.floor(percent);
document.getElementById("lovexin12").style.top=parseInt(document.getElementById("lovexin12").style.top)+percent+"px";
document.getElementById("lovexin14").style.top=parseInt(document.getElementById("lovexin12").style.top)+percent+"px";

lastScrollY=lastScrollY+percent;
//alert(lastScrollY);
}
suspendcode12="<DIV id=\"lovexin12\" style='left:2px;POSITION:absolute;TOP:120px;'>ad1</div>"
suspendcode14="<DIV id=\"lovexin14\" style='right:2px;POSITION:absolute;TOP:120px;'>ad2</div>"
document.write(suspendcode12);
document.write(suspendcode14);
window.setInterval("heartBeat()",1);


评论: 0 | 引用: 0 | 查看次数: 4251
发表评论
登录后再发表评论!