javascript 简单的拖放代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18425089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:52:54  来源:igfitidea点击:

Simple drag and drop code

javascriptdrag-and-dropdraggabledrag

提问by Kayote

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:

我正在为看似简单的 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);
}

采纳答案by iRector

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

这是一个可以工作的 jsfiddle:http: //jsfiddle.net/fpb7j/1/

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

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

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

while mousedown, mousemoveand mouseupare for event listeners:

消磨mousedownmousemove并且mouseup是事件监听器:

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:

第二个问题是移动事件函数中的 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);
}

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

顺便说一句,我必须使目标的位置绝对化才能使其工作。

回答by dennisbot

you can try this fiddle too, http://jsfiddle.net/dennisbot/4AH5Z/

你也可以试试这个小提琴,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>

回答by ling

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

这是一种单行用法,它处理诸如鼠标到元素左上角的偏移、onDrag/onStop 回调和 SVG 元素拖动之类的事情

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:

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

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

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

在此处查看我的仓库以获取更多详细信息:https: //github.com/lingtalfi/simpledrag