简单拖动层
View Code
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>drag div demo</title> <style type="text/css"> <!-- #dragDiv { position:absolute; width:200px; height:115px; z-index:1; left: 40px; top: 51px; background-color: #3300CC; cursor:pointer; } --> </style> <script type="text/javascript"> function addEvent(obj,name,handler,useCapture) //封装好的注册事件函数 { if(window.event) { obj.attachEvent('on' + name,handler); } else { obj.addEventListener(name,handler,useCapture); } } var dragable = false; //当前是否拖动的开关 var mousePosition = []; //鼠标位置缓存 /* * mousedown事件处理函数。当mousedown事件触发时,将dragable开关设置为true,并且读取鼠标位置存入mousePosition数组。 */ function mousedownEventHandler(evt) { dragable = true; var evt = evt || event; var mouseX = (document.body.scrollLeft || document.documentElement.scrollLeft) + evt.clientX; var mouseY = (document.body.scrollTop || document.documentElement.scrollTop) + evt.clientY; mousePosition = [mouseX,mouseY]; } /* * mousemove事件处理函数。当mousemove事件触发时,读取鼠标当前位置和鼠标位置混存比较,然后将差值增加到div的坐标中,达到移动div的效果。 */ function mousemoveEventHandler(evt) { if(!dragable) //如果dragable为false,则不执行拖动 { return; } var evt = evt || event; var mouseX = (document.body.scrollLeft || document.documentElement.scrollLeft) + evt.clientX; var mouseY = (document.body.scrollTop || document.documentElement.scrollTop) + evt.clientY; div.style.left = div.offsetLeft + mouseX - mousePosition[0] + 'px'; div.style.top = div.offsetTop + mouseY - mousePosition[1] + 'px'; mousePosition = [mouseX,mouseY]; //每一次拖动完成后,更新鼠标位置缓存 } /* * mouseup事件处理函数。当mouseup事件触发时,将dragable开关设置为false,停止拖动。 */ function mouseupEventHandler() { dragable = false; } function init() //初始化程序 { div = document.getElementById('dragDiv'); addEvent(div,'mousedown',mousedownEventHandler,false); addEvent(document,'mousemove',mousemoveEventHandler,false); addEvent(div,'mouseup',mouseupEventHandler,false); } window.onload = init; //在窗体加载完成时初始化程序 </script> </head> <body> <div id="dragDiv"></div> </body> </html>
道之所在,虽千万人吾往矣