使用JavaScript实现上下浮动的窗口效果。其中主要使用setTimeout函数实现定时设置窗口的left和top值,以实现窗口的上下左右移动。下面是实现代码:
<html> <head> <title>上下浮动的窗口</title> <script type="text/javascript"> var stepLength = 1; // 移动步长,此参数越小,移动越平滑,最小值为1 var delay_time = 160; // 每步的时间间隔,此参数越小,移动速度越快 var upDownState = 0; // 浮动层上下移状态(0-上移、非0-下移) var xLength = 10; // 浮动层的X坐标,即左边距 var yLength = 0; // 浮动层的Y坐标,即上边距 var bodyHeight = 0; // 页面高度 var divHeight = 0; // 浮动层高度 // 判断浏览器是否是IE、NS4、NS6 var ns4 = document.layers ? 1 : 0; var ie = document.all ? 1 : 0; var ns6 = (document.getElementById && !document.all) ? 1 : 0; window.onload = function(){ // 获得页面的高度,然后将浮动层的上边距设置为页面高度 if(ie){ yLength = document.body.clientHeight; floatpoint.style.top = yLength; } else if (ns4){ yLength = window.innerHeight; document.floatpoint.pageY = yLength; document.floatpoint.visibility = "hidden"; } else if (ns6){ yLength=window.innerHeight document.getElementById('floatpoint').style.top=yLength } if (ie || ns4 || ns6) { if(ns4) { document.floatpoint.visibility = "visible"; } loopSetPosition(); } }; /** * 循环设置浮动层的位置 */ function loopSetPosition(){ resetLocation(); // 设定下一次调整的延时 setTimeout(function(){ loopSetPosition(); }, delay_time); } /** * 设置浮动块的位置 */ function resetLocation(){ // 根据浮动层上下移动状态设置上边距 if(upDownState == 0){ yLength = yLength - stepLength; // 如果上移,则减小yLength值 } else{ yLength = yLength + stepLength; // 否则增加yLength值下移 } // 取出页面高度和浮动层高度 if (ie){ bodyHeight = document.body.clientHeight; divHeight = floatpoint.offsetHeight; } else if (ns4){ bodyHeight = window.innerHeight; divHeight = document.floatpoint.clip.height; } else if (ns6){ bodyHeight = window.innerHeight; divHeight = document.getElementById("floatpoint").offsetHeight; } // 如果浮动层超出了上界,则设定移动方向为向下;并设定层的位置为正好在上界处 if(yLength < 0){ upDownState = 1; yLength = 0; } // 如果浮动层超出了下界,则设定移动方向为向上;并设定层的位置为正好在下界处 if(yLength >= (bodyHeight-divHeight)){ upDownState = 0; yLength = (bodyHeight-divHeight); } // 设置浮动层的左边距和上边距 if(ie){ floatpoint.style.left = xLength; floatpoint.style.top = yLength+document.body.scrollTop; } else if (ns4){ document.floatpoint.pageX = xLength; document.floatpoint.pageY = yLength + window.pageYOffset; } else if (ns6){ document.getElementById("floatpoint").style.left = xLength document.getElementById("floatpoint").style.top = yLength + window.pageYOffset } } </script> </head> <body> <!-- 浮动层HTML定义 --> <div id="floatpoint" style="position: absolute; visibility: visible; border: solid 1px #E3E3E3;"> <table border="0" cellspacing="0" cellpadding="0"> <tr height="25px"> <td style="background-color:#E3E3E3; font-size:12px; color:#606070;"> 最新消息</td> </tr> <tr> <td> <div style="height:100px; width:170px; font-size:12px; padding:4px; color:#808080;"> 将要显示的内容。可以是广告、提示信息…… </div> </td> </tr> </table> </div> </body> </html>
运行效果如下图所示: