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

Javascript
有趣的script标签用getAttribute方法来自脚本吧
学习YUI.Ext 第二天
学习YUI.Ext 第三天
学习YUI.Ext第五日--做拖放Darg&Drop
学习YUI.Ext 第六天--关于树TreePanel(Part 1)
学习YUI.Ext 第七天--关于View&JSONView
学习YUI.Ext 第六天--关于树TreePanel(Part 2异步获取节点)
对YUI扩展的Gird组件 Part-2
Gird事件机制初级读本
为Yahoo! UI Extensions Grid增加内置的可编辑器
如何简单地用YUI做JavaScript动画
(function(){})()的用法与优点
JS层移支示例代码
如何在Web页面上直接打开、编辑、创建Office文档
网页中实现浏览器的最大,最小化和关闭按钮
[原创]js与自动伸缩图片 自动缩小图片的多浏览器兼容的方法总结
图片自动缩小的js代码,用以防止图片撑破页面
收藏一些不常用,但是有用的代码
解决 firefox 不支持 document.all的方法
用ajax实现的自动投票的代码

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 174 ::
收藏到网摘: 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)