Ajax的兴起,造就了很多Web体验的产生,移动层即为其中一种产物,目的是让页面上的可以产生一个可以移动的图层,来模拟alert弹出窗口,让用户很平滑的在同一页面上进行操作。
网上参考代码:
<html> <head> <title>测试可移动层</title> <script> var mydiv = null; var x,y; var lefttemp,toptemp; function newDiv(){ } function startDrag(){ mydiv = document.getElementById("testDiv"); lefttemp = mydiv.style.pixelLeft; toptemp = mydiv.style.pixelTop; x = event.clientX; y = event.clientY; document.onmousemove = drag; document.onmouseup = endDrag; } function endDrag(){ document.οnmοusemοve=""; document.οnmοuseup=""; } function drag(){ mydiv.style.pixelLeft = lefttemp + event.clientX - x; mydiv.style.pixelTop = toptemp + event.clientY - y; } </script> </head> <body> <div id="testDiv" style="width:392px; height:154px; background-color:#6633CC; position:absolute; left:60px; top:48px;"> <table width="100%" height="26" border="0" cellpadding="0" cellspacing="0" bgcolor="#33FF33" onMouseDown="startDrag();"> <tr> <td> </td> </tr> </table> </div> </body> </html>
个人的尝试:
<html> <head> <title>测试可移动层</title> <script> var mydiv = null; var x,y; var lefttemp,toptemp; function newDiv(){ } function startDrag(){ mydiv = document.getElementById("testDiv"); lefttemp = mydiv.style.pixelLeft; toptemp = mydiv.style.pixelTop; x = event.clientX; y = event.clientY; document.onmousemove = drag; document.onmouseup = endDrag; } function endDrag(){ document.οnmοusemοve=""; document.οnmοuseup=""; } function drag(){ mydiv.style.pixelLeft = lefttemp + event.clientX - x; mydiv.style.pixelTop = toptemp + event.clientY - y; } </script> </head> <body> <div id="testDiv" style="width:392px; height:154px; background-color:#6633CC; position:absolute; left:60px; top:48px;"> <table width="100%" height="26" border="0" cellpadding="0" cellspacing="0" bgcolor="#33FF33" onMouseDown="startDrag();"> <tr> <td> </td> </tr> </table> </div> </body> </html>
虽然现在有像jQuery这么流行的前端库做移动层的支撑,但是如果不去琢磨一下的话,也许永远也不会知道其中的原理。