JavaScript页面内拖拽原理分析
2010-11-13 08:04:44 来源:WEB开发网核心提示: HTML代码<div id="test" style="border:1px solid; width:400px; background:#CCCCCC;"> <p>我是拖拽示例DIV,</p> <p>可以试验一下效
- <div id="test" style="border:1px solid; width:400px; background:#CCCCCC;">
- <p>我是拖拽示例DIV。</p>
- <p>可以试验一下效果。</p>
- </div>
演示代码
<!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>JavaScript拖拽示例网页</title> <mce:script type="text/javascript"><!-- var dragging = false; var test; var mouseY; var mouseX; window.onload = function(){ test = document.getElementById("test"); test.onmousedown = down; test.onmousemove = move; document.onmouseup = up; test.style.position = "relative"; test.style.top = "0px"; test.style.left = "0px"; } function down(event) { eventevent = event || window.event; dragging = true; mouseX = parseInt(event.clientX); mouseY = parseInt(event.clientY); objY = parseInt(test.style.top); objX = parseInt(test.style.left); } function move(event){ eventevent = event || window.event; if(dragging == true){ var x,y; y = event.clientY - mouseY + objY; x = event.clientX - mouseX + objX; test.style.top = y + "px"; test.style.left = x + "px"; } } function up(){ dragging = false; } // --></mce:script> </head> <body> <div id="test" style="border:1px solid; width:400px; background:#CCCCCC;"> <p>我是拖拽示例DIV。</p> <p>可以试验一下效果。</p> </div> </body> </html>
缺点与待完善之处
这个拖拽的例子还相当不完善,不过已经实现了拖拽最根本的核心。想到的待完善部分有下面几点:获得元素的x与y坐标的方法在本文里简化掉了;本文只让一个固定的元素具有了拖拽功能,灵活性太差;鼠标样式没有变换;快速的“乱甩拖拽”有一定概率出现问题。其中最后一个问题暂时不知道怎么解决,前面三个比较好办。
Tags:JavaScript 页面 原理
编辑录入:爽爽 [复制链接] [打 印]更多精彩
赞助商链接