1. 浮动层的显示、移动
一个简单的例子:<div id="mydiv" style="position:absolute;">my div contents</div><script language="javascript">var dX = 10;var dY = 10;function mydivMove(x, y){ var id = 'mydiv'; if (document.layers){ document.layers[''+id+''].left = x; document.layers[''+id+''].top = y; } else if (document.all){ document.all[''+id+''].style.left=x; document.all[''+id+''].style.top=y; } else if (document.getElementById){ document.getElementById(''+id+'').style.left=x+"px"; document.getElementById(''+id+'').style.top=y+"px"; }}
mydivMove(dX,dY);</script>
主要的问题在于不同浏览器对于层的坐标获取方式不同,尤其要注意当通过getElementById来获取层坐标的时候(非IE浏览器),改变坐标的时候要加上"px"后缀,而不是直接进行数字赋值。
2. 关于window.onscroll
g_myBodyInstance = (document.documentElement ? document.documentElement : window);g_myBodyInstance.onscroll = mydivScrollFunc;
上面的代码实现了兼容的onscroll事件处理。可以看到对于Firefox来说onscroll事件是隶属于document.documentElement对象而不是window对象。
但似乎Firefox浏览器对于通过鼠标中键滚动页面的操作并不会去触发onscroll事件,而只有拖动右边的窗口滚动条才会触发,这给我带来极大的困扰,这样如果想要让用户浏览页面的任何时候某个浮动层(比如我的导航条)始终位于页面可见范围的话,就不得不使用setInterval或者setTimeout来不停的改变这个浮动层的位置。而不能采用触发onscroll、onresize这两个事件进行显示位置重置。这显然是低效率的方法。幸好标准XHTML提供了一个CSS属性值,可以通过设置这个值来曲线达到目的:<script>var id = 'mydiv';if (document.layers){ document.layers[''+id+''].position = 'fixed';}else if (document.all){ document.all[''+id+''].style.position='fixed';}else if (document.getElementById){ document.getElementById(''+id+'').style.position='fixed';}</script>
position的fixed属性让该层能够始终位于窗口的指定位置。从显示效果来看,在Firefox上的显示效果比IE中通过onscroll触发层的位置移动处理显示效果要好很多,看不到层的闪动。
Updated 2005-9-23 14:24 -- 学海无涯提供了另外的一种实现移动层的方法:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" ><head><style type="text/css">body { margin:0; /* 必须 */ border:0; height:100%; /* 必须 */ overflow-y:auto;/* 必须 */ }#menu {display:block; top:10px; left:150px; width:130px; position:fixed;} /* IE并不认识fixed,而FF认识 */* html #menu {position:absolute;} /* 这个只有IE认识 */</style><!--[if IE 6]> <style type="text/css"> /*<![CDATA[*/ html {overflow-x:auto; overflow-y:hidden;} /*]]>*/ </style><![endif]--></head><body><div><ul style="list-style-type:decimal"><script language=javascript>for(i=0;i<500;i++) document.write('<li></li>');</script></ul></div><div id="menu"><img src="http://www.cnblogs.com/images/cnblogs_com/goodspeed/795/o_o_mylogo.gif" /></div></body></html>
据说IE7已提供了fixed的支持。
使用上面的代码你必须注意:body里的元素不能有 position:relative ,否则这个元素将不会滚动。
3. 关于onmousemove
对于IE来说,模拟鼠标拖放操作相关处理如下:// 捕获鼠标移动mydiv.setCapture();document.onmousemove = mydivMoveFunc;// 释放鼠标移动mydiv.releaseCapture();document.onmousemove = null;
对于Firefox浏览器来说,要这样处理:// 捕获鼠标移动window.captureEvents(Event.MOUSEMOVE);window.onmousemove = mydivMoveFunc;// 释放鼠标移动window.releaseEvents(Event.MOUSEMOVE);window.onmousemove = null;
可见IE支持细化到某个层的事件捕获,而Firefox只能是捕获整个页面所有的相同事件。从实际显示效果来看,IE的表现出来的拖拉效果要明显好一些。关于完整的鼠标拖放的实现可以参见可移动层的实现示例一文