简单的拖放代码

时间:2013-08-25 02:27:13

标签: javascript drag-and-drop draggable drag

我正在努力寻找一个简单的javascript练习,写一个香草拖放。我想我的'addeventlisteners'犯了一个错误,这是代码:

var ele = document.getElementsByClassName ("target")[0];
var stateMouseDown = false;
//ele.onmousedown = eleMouseDown;
ele.addEventListener ("onmousedown" , eleMouseDown , false);

function eleMouseDown () {
    stateMouseDown = true;
    document.addEventListener ("onmousemove" , eleMouseMove , false);
}

function eleMouseMove (ev) {
    do {
        var pX = ev.pageX;
        var pY = ev.pageY;
        ele.style.left = pX + "px";
        ele.style.top = pY + "px";
        document.addEventListener ("onmouseup" , eleMouseUp , false);
    } while (stateMouseDown === true);
}

function eleMouseUp () {
    stateMouseDown = false;
    document.removeEventListener ("onmousemove" , eleMouseMove , false);
    document.removeEventListener ("onmouseup" , eleMouseUp , false);
}

4 个答案:

答案 0 :(得分:11)

这是一个有效的jsfiddle:http://jsfiddle.net/fpb7j/1/

有两个主要问题,首先是使用onmousedownonmousemoveonmouseup。我相信这些只会与附加事件一起使用:

document.body.attachEvent('onmousemove',drag);

mousedownmousemovemouseup用于事件监听器:

document.body.addEventListener('mousemove',drag);

第二个问题是移动事件功能中的do-while循环。每次鼠标移动一个像素时都会调用该函数,因此不需要循环:

var ele = document.getElementsByClassName ("target")[0];
ele.addEventListener ("mousedown" , eleMouseDown , false);

function eleMouseDown () {
    stateMouseDown = true;
    document.addEventListener ("mousemove" , eleMouseMove , false);
}

function eleMouseMove (ev) {
    var pX = ev.pageX;
    var pY = ev.pageY;
    ele.style.left = pX + "px";
    ele.style.top = pY + "px";
    document.addEventListener ("mouseup" , eleMouseUp , false);
}

function eleMouseUp () {
    document.removeEventListener ("mousemove" , eleMouseMove , false);
    document.removeEventListener ("mouseup" , eleMouseUp , false);
}

顺便说一下,我必须让目标的位置绝对让它发挥作用。

答案 1 :(得分:11)

你也可以试试这个小提琴,http://jsfiddle.net/dennisbot/4AH5Z/

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>titulo de mi pagina</title>
<style>
    #target {
        width: 100px;
        height: 100px;
        background-color: #ffc;
        border: 2px solid blue;
        position: absolute;
    }
</style>
<script>
   window.onload = function() {
        var el = document.getElementById('target');
        var mover = false, x, y, posx, posy, first = true;
        el.onmousedown = function() {
            mover = true;
        };
        el.onmouseup = function() {
            mover = false;
            first = true;
        };
        el.onmousemove = function(e) {
            if (mover) {
                if (first) {
                    x = e.offsetX;
                    y = e.offsetY;
                    first = false;
                }
                posx = e.pageX - x;
                posy = e.pageY - y;
                this.style.left = posx + 'px';
                this.style.top = posy + 'px';
            }
        };
   }
</script>
</head>
<body>
    <div id="target" style="left: 10px; top:20px"></div>
</body>
</html>

答案 2 :(得分:1)

我只是拖了一下。

它是一个单行使用,它处理诸如鼠标偏移到元素左上角,onDrag / onStop回调和SVG元素拖动等事情

这是代码。

// simple drag
function sdrag(onDrag, onStop) {
    var startX = 0;
    var startY = 0;
    var el = this;
    var dragging = false;

    function move(e) {
        el.style.left = (e.pageX - startX ) + 'px';
        el.style.top = (e.pageY - startY ) + 'px';
        onDrag && onDrag(el, e.pageX, startX, e.pageY, startY);
    }

    function startDragging(e) {
        if (e.currentTarget instanceof HTMLElement || e.currentTarget instanceof SVGElement) {
            dragging = true;
            var left = el.style.left ? parseInt(el.style.left) : 0;
            var top = el.style.top ? parseInt(el.style.top) : 0;
            startX = e.pageX - left;
            startY = e.pageY - top;
            window.addEventListener('mousemove', move);
        }
        else {
            throw new Error("Your target must be an html element");
        }
    }

    this.addEventListener('mousedown', startDragging);
    window.addEventListener('mouseup', function (e) {
        if (true === dragging) {
            dragging = false;
            window.removeEventListener('mousemove', move);
            onStop && onStop(el, e.pageX, startX, e.pageY, startY);
        }
    });
}

Element.prototype.sdrag = sdrag;

并使用它:

document.getElementById('my_target').sdrag();

您还可以使用onDrag和onStop回调:

document.getElementById('my_target').sdrag(onDrag, onStop);

点击此处查看我的回购详情:  https://github.com/lingtalfi/simpledrag

答案 3 :(得分:1)

这就是我的做法

var MOVE = {
  startX: undefined,
  startY: undefined,
  item: null
};

function contentDiv(color, width, height) {
  var result = document.createElement('div');
  result.style.width = width + 'px';
  result.style.height = height + 'px';
  result.style.backgroundColor = color;
  return result;
}

function movable(content) {
  var outer = document.createElement('div');
  var inner = document.createElement('div');
  outer.style.position = 'relative';
  inner.style.position = 'relative';
  inner.style.cursor = 'move';
  inner.style.zIndex = 1000;
  outer.appendChild(inner);
  inner.appendChild(content);
  inner.addEventListener('mousedown', function(evt) {
    MOVE.item = this;
    MOVE.startX = evt.pageX;
    MOVE.startY = evt.pageY;
  })
  return outer;
}

function bodyOnload() {
  document.getElementById('td1').appendChild(movable(contentDiv('blue', 100, 100)));
  document.getElementById('td2').appendChild(movable(contentDiv('red', 100, 100)));
  document.addEventListener('mousemove', function(evt) {
    if (!MOVE.item) return;
    if (evt.which!==1){ return; }
    var dx = evt.pageX - MOVE.startX;
    var dy = evt.pageY - MOVE.startY;
    MOVE.item.parentElement.style.left = dx + 'px';
    MOVE.item.parentElement.style.top = dy + 'px';
  });
  document.addEventListener('mouseup', function(evt) {
    if (!MOVE.item) return;
    var dx = evt.pageX - MOVE.startX;
    var dy = evt.pageY - MOVE.startY;
    var sty = MOVE.item.style;
    sty.left = (parseFloat(sty.left) || 0) + dx + 'px';
    sty.top = (parseFloat(sty.top) || 0) + dy + 'px';
    MOVE.item.parentElement.style.left = '';
    MOVE.item.parentElement.style.top = '';
    MOVE.item = null;
    MOVE.startX = undefined;
    MOVE.startY = undefined;
  });
}
bodyOnload();
table {
user-select: none
}
<table>
  <tr>
    <td id='td1'></td>
    <td id='td2'></td>
  </tr>
</table>

在拖动时,被拖动元素的parentElement样式的leftright不断更新。然后,可以说,在mouseup(='drop')上,“更改已提交”;我们将父元素的(水平和垂直)位置变化(即,左侧和顶部)添加到元素本身的位置,然后再次清除父元素的左侧/顶部。这样,我们只需要将JavaScript变量用于pageX,pageY(拖动开始时的鼠标位置),而在拖动开始时考虑元素位置,就不需要JavaScript变量(只需将信息保留在DOM中)。

如果要处理SVG元素,则可以使用相同的父/子/提交技术。只需使用两个嵌套的g,然后使用transform=translate(dx,dy)代替style.left=dxstyle.top=dy