Simple drag and drop code

拜拜、爱过 提交于 2020-01-22 09:30:10

问题


Im struggling with seemingly a simple javascript exercise, writing a vanilla drag and drop. I think Im making a mistake with my 'addeventlisteners', here is the code:

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);
}

回答1:


Here's a jsfiddle with it working: http://jsfiddle.net/fpb7j/1/

There were 2 main issues, first being the use of onmousedown, onmousemove and onmouseup. I believe those are only to be used with attached events:

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

while mousedown, mousemove and mouseup are for event listeners:

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

The second issue was the do-while loop in the move event function. That function's being called every time the mouse moves a pixel, so the loop isn't needed:

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);
}

By the way, I had to make the target's position absolute for it to work.




回答2:


you can try this fiddle too, 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>



回答3:


I've just made a simple drag.

It's a one liner usage, and it handles things like the offset of the mouse to the top left corner of the element, onDrag/onStop callbacks, and SVG elements dragging

Here is the code.

// 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;

and to use it:

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

You can also use onDrag and onStop callbacks:

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

Check my repo here for more details: https://github.com/lingtalfi/simpledrag



来源:https://stackoverflow.com/questions/18425089/simple-drag-and-drop-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!