实现拖拽的基本思路
拖拽的基本原理就是根据鼠标的移动来移动被拖拽的元素。鼠标的移动也就是x、y坐标的变化;元素的移动就是style.position的top和left的改变。当然,并不是任何时候移动鼠标都要造成元素的移动,而应该判断鼠标左键的状态是否为按下状态,是否是在可拖拽的元素上按下的。
根据以上的基本原理,我写出了下面的基本思路。感觉代码还是比较短的,
- 拖拽状态 = 0鼠标在元素上按下的时候{
- 拖拽状态 = 1
- 记录下鼠标的x和y坐标
- 记录下元素的x和y坐标
- }
- 鼠标在元素上移动的时候{
- 如果拖拽状态是0就什么也不做。
- 如果拖拽状态是1,那么
- 元素y = 现在鼠标y - 原来鼠标y + 原来元素y
- 元素x = 现在鼠标x - 原来鼠标x + 原来元素x
- }
- 鼠标在任何时候放开的时候{
- 拖拽状态 = 0
- }
将以上思路翻译成JS代码就可以实现拖拽的效果了。
JavaScript代码
- <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>
- <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坐标的方法在本文里简化掉了;本文只让一个固定的元素具有了拖拽功能,灵活性太差;鼠标样式没有变换;快速的“乱甩拖拽”有一定概率出现问题。其中最后一个问题暂时不知道怎么解决,前面三个比较好办。