Drag and drop anywhere on screen with multiple elements of the same ID Class and Tag HTML

前端 未结 2 492
北恋
北恋 2021-01-16 02:13

Hello everyone this is my first question so I might have done it wrong. What I am trying to achieve is is have multiple

2条回答
  •  粉色の甜心
    2021-01-16 02:46

    The following code will allow drag and drop; I'm sorry it doesn't follow your previous coding style.

    Here is a JSFiddle showing it in action: https://jsfiddle.net/6gq7u8Lc/

        document.getElementById("dragme").onmousedown = function(e) {
            this.prevX = e.clientX;
            this.prevY = e.clientY;
            this.mouseDown = true;
        }
        document.getElementById("dragme").onmousemove = function(e) {
            if(this.mouseDown) {
                this.style.left = (Number(this.style.left.substring(0, this.style.left.length-2)) + (e.clientX - this.prevX)) + "px";
                this.style.top = (Number(this.style.top.substring(0, this.style.top.length-2)) + (e.clientY - this.prevY)) + "px";
            }
            this.prevX = e.clientX;
            this.prevY = e.clientY;
        }
        document.getElementById("dragme").onmouseup = function() {
            this.mouseDown = false;
        }
    

    On a side note, you won't be able to give them all the same id. The DOM doesn't support such a thing. If you want to add multiple elements of the same type, I would suggest a 'container' parent div, adding the elements as children of the div, and iterating through the .children attribute to access each.

提交回复
热议问题