当前位置: 首页 > 图文教程 > 网络编程 > Javascript > javascript跟随滚动条滚动的层(浮动AD效果)

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 javascript跟随滚动条滚动的层(浮动AD效果)


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 138 ::
收藏到网摘: n/a

其实这个效果在很多网站中都能见到,其主要表现为网页两侧的浮动广告。看起来感觉很难做,但其实原理是很简单的,使用定时器没0.1秒检测层的位置并将其置在指定的位置(相对于窗口)。写了一个简单的代码:
点击运行可以看到效果:
[Ctrl+A 全选 提示:你可先修改部分代码,再按运行]

注意:
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)