【问题标题】:JavaScript - How to make multiple divs draggable and movable across the websiteJavaScript - 如何使多个 div 可在网站上拖动和移动
【发布时间】:2018-07-18 19:26:49
【问题描述】:

我希望我的网站上有多个 div 可以在整个网站(或至少在找到它的容器中)可拖动和移动。

我想澄清一下,我在网络和 Stackoverflow 上搜索了多次,但所有这些都通过使用 jQuery 或其他一些库来建议答案。我想要一种纯 JavaScript 方式在整个网站上移动多个 div(希望只有一个功能)。

我正在做的项目是练习使用 HTML 和 JS 拖放,我在容器“x”中有 4 个 div(其中包含图像)和另一个容器“y”来拖放这些 div那个容器'y',但是如果我将它们全部拖到那里,第一个 div 只会设置到左上角,其余的设置在它们下面(或者如果我将它们的显示设置为内联块,则它们并排)。所以,我想让这些 div 在我拖入的容器“y”上移动,以便在需要的地方移动它们。 (它们也可以调整大小)。

拖放 JavaScript 和 HTML 代码(不包括 CSS 和一些不必要的 HTML 代码)是这样的:

function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
    ev.dataTransfer.dropEffect = "move";
}

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    ev.target.appendChild(document.getElementById(data));
}
<div id="images-container" ondrop="drop(event)" ondragover="allowDrop(event)">

      <div class="resize" style="background: url('images/photo-1.jpg') center no-repeat; background-size: cover; background-position: center center;" id="drag1" draggable="true" ondragstart="drag(event)">
      </div>
      <div class="resize" style="background: url('images/photo-2.jpg') center no-repeat; background-size: cover; background-position: center center;" id="drag2" draggable="true" ondragstart="drag(event)">
      </div>
      <div class="resize" style="background: url('images/photo-3.jpg') center no-repeat; background-size: cover; background-position: center center;" id="drag3" draggable="true" ondragstart="drag(event)">
      </div>
      <div class="resize" style="background: url('images/photo-4.jpg') center no-repeat; background-size: cover; background-position: center center;" id="drag4" draggable="true" ondragstart="drag(event)">
      </div>

 </div>

 <div id="gallery" ondrop="drop(event)" ondragover="allowDrop(event)"></div>

我查看了 W3schools 的 this 文章,但它只适用于一个 div 元素,因为它是使用 ID 构建的,但是我可以用这段代码做什么才能将它用于多个 div 和我猜的类?如果有其他方法,我会很高兴听到一些关于它的建议,尽管是在纯 JavaScript 中。

谢谢。

【问题讨论】:

  • 你回答了你自己的问题,这里有工作示例如何做到这一点:w3schools.com/howto/howto_js_draggable.asp 只需添加另一个具有不同 id 的 div
  • @Rainmx93 我知道,我完全理解,但为此,我应该为 4 个不同的 ID 提供 4 个函数,但我想为所有 div 提供一个函数,可能具有相同的类或具有查询选择器,但我不确定如何更改函数以使用给定 div 的类。任何建议将不胜感激。

标签: javascript drag-and-drop draggable


【解决方案1】:

我猜你现在可能已经整理好了。我会在这里为像我这样正在寻找答案的人发布这个。我认为 w3Schools 示例也仅适用于单个元素。它实际上仅通过调用每个元素的函数即可处理多个元素。

var draggableElements = document.getElementsByClassName("draggable");

for(var i = 0; i < draggableElements.length; i++){
    dragElement(draggableElements[i]);
}

function dragElement(elmnt) {
    var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
    if (document.getElementById(elmnt.id + "header")) {
        document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
    } else {
        elmnt.onmousedown = dragMouseDown;
    }
    function dragMouseDown(e) {
        e = e || window.event;
        pos3 = parseInt(e.clientX);
        pos4 = parseInt(e.clientY);
        document.onmouseup = closeDragElement;
        document.onmousemove = elementDrag;
        return false;
    }

    function elementDrag(e) {
        e = e || window.event;
        pos1 = pos3 - parseInt(e.clientX);
        pos2 = pos4 - parseInt(e.clientY);
        pos3 = parseInt(e.clientX);
        pos4 = parseInt(e.clientY);
        elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
        console.log(elmnt.offsetTop)
        elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
    }

    function closeDragElement() {
        document.onmouseup = null;
        document.onmousemove = null;
    }
}

现在,起初这给了我奇怪的结果。当我移动鼠标时,我的 div 只向一个方向移动,如果你在 div 上有边距,它会弄乱计算。因此,要么不使用边距,要么编辑代码以供他们使用。

W3Schools 原文链接:https://www.w3schools.com/howto/howto_js_draggable.asp

【讨论】:

  • 是的,没关系。这是一个小项目来练习 JavaScript 及其拖放功能。如果我需要在未来的网站或项目中实现这样的功能,我一定会回复您的答案以获取有关此功能的更多信息。谢谢。
【解决方案2】:

这对我有用。没有使用 JQuery。

我生成了 4 个 div,所有这些 div 都在彼此之上,但它们可以被拖动。 当你点击一个 div 时,它的边框会亮起,你可以拖动它。拖动的 div 移动到其他 div 的前面。因为它看起来很有趣,所以我使用画布在 div 之间绘制了曲线。

<!doctype html>
<html>
    <head>
        <style>
            div {
            position: absolute;
            top: 0;
            height: 60px;
            width: 100px;
            background: #15a5ed;
            text-align: center;
            line-height: 60px;
            border-radius: 15px 15px 15px 15px;
            }
        </style>
    </head>
    <body>
        <canvas id="canvas" class="canvas"></canvas>
        <div id="div1">Me</div>
        <div id="div2">You</div>
        <div id="div3">Us</div>
        <div id="div4">Them</div>
        <script>
            divs = document.getElementsByTagName("div");
            for (div of divs) div.onmousedown = onMouseDown;
            
            document.onmousemove = onMouseMove;
            document.onmouseup   = onMouseUp;
            
            canvas.width = window.innerWidth - 20;
            canvas.height = window.innerHeight - 20;
            
            var the_moving_div = ''; 
            var the_last_mouse_position = { x:0, y:0 };
            
            drawConnectors();
            
            function onMouseDown(e) {
                e.preventDefault();
                the_moving_div            = e.target.id;      // remember which div has been selected 
                the_last_mouse_position.x = e.clientX;        // remember where the mouse was when it was clicked
                the_last_mouse_position.y = e.clientY;
                e.target.style.border = "2px solid blue";     // highlight the border of the div
            
                var divs = document.getElementsByTagName("div");
                e.target.style.zIndex = divs.length;          // put this div  on top
                var i = 1; for (div of divs) if (div.id != the_moving_div) div.style.zIndex = i++;   // put all other divs behind the selected one
            }
            
            function onMouseMove(e) {
                e.preventDefault();
                if (the_moving_div == "") return;
                var d = document.getElementById(the_moving_div);
                d.style.left = d.offsetLeft + e.clientX - the_last_mouse_position.x + "px";     // move the div by however much the mouse moved
                d.style.top  = d.offsetTop  + e.clientY - the_last_mouse_position.y + "px";
                the_last_mouse_position.x = e.clientX;                                          // remember where the mouse is now
                the_last_mouse_position.y = e.clientY;
                drawConnectors();
            }
            
            function onMouseUp(e) {
                e.preventDefault();
                if (the_moving_div == "") return;
                document.getElementById(the_moving_div).style.border = "none";             // hide the border again
                the_moving_div = "";
            }
            
            function drawConnectors() {
                var canvas = document.getElementById('canvas');
                var ctx = canvas.getContext('2d');
                ctx.clearRect(0,0,canvas.width,canvas.height);
                ctx.beginPath();
                ctx.strokeStyle="#15a5ed";
                ctx.lineWidth=3;
                for (div1 of divs) for (div2 of divs) {
                    if (div1 == div2) continue;
                    ctx.moveTo(div1.offsetLeft + div1.clientWidth/2, div1.offsetTop + div1.clientHeight/2);
                    ctx.bezierCurveTo(div1.offsetLeft, div1.offsetTop, 
                                      div2.offsetLeft, div2.offsetTop, 
                                      div2.offsetLeft + div2.clientWidth/2, div2.offsetTop + div2.clientHeight/2);
                    ctx.stroke();                   
                }
            }
        </script>
    </body>
</html>

【讨论】:

    【解决方案3】:

    我玩过这个。使用 w3 学校示例。我对此进行了扩展以使其具有动态性(可选类)。

    这是使它工作的 JavaScript。

    document.addEventListener('DOMContentLoaded', function () {
        //Make the DIV element draggagle:
    
        members = document.querySelectorAll('.mover').forEach(item => {
            item.addEventListener('mousedown', ev => {
                console.log(ev);
                let tid;
                tid = ev.target.id;
                if (ev.target.id == "") {
                    tid = ev.target.parentNode.id;
                }
                dragElement(document.getElementById(tid));
            })
        })
    
        function dragElement(elmnt) {
            var pos1 = 0,
                pos2 = 0,
                pos3 = 0,
                pos4 = 0;
            if (document.getElementById(elmnt.id + 'header')) {
                /* if present, the header is where you move the DIV from:*/
                document.getElementById(elmnt.id + 'header').onmousedown =
                    dragMouseDown;
            } else {
                /* otherwise, move the DIV from anywhere inside the DIV:*/
                elmnt.onmousedown = dragMouseDown;
            }
    
            function dragMouseDown(e) {
                e = e || window.event;
                e.preventDefault();
                // get the mouse cursor position at startup:
                pos3 = e.clientX;
                pos4 = e.clientY;
                document.onmouseup = closeDragElement;
                // call a function whenever the cursor moves:
                document.onmousemove = elementDrag;
            }
    
            function elementDrag(e) {
                e = e || window.event;
                e.preventDefault();
                // calculate the new cursor position:
                pos1 = pos3 - e.clientX;
                pos2 = pos4 - e.clientY;
                pos3 = e.clientX;
                pos4 = e.clientY;
                // set the element's new position:
                elmnt.style.top = elmnt.offsetTop - pos2 + 'px';
                elmnt.style.left = elmnt.offsetLeft - pos1 + 'px';
            }
    
            function closeDragElement() {
                /* stop moving when mouse button is released:*/
                document.onmouseup = null;
                document.onmousemove = null;
            }
        }
    });
    

    注意我所做的更改:

    • DOM Lister 包装代码。
    • 分配给“.mover”类的mousedown监听器

    【讨论】:

      猜你喜欢
      • 2012-03-09
      • 2014-07-25
      • 1970-01-01
      • 1970-01-01
      • 2013-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-28
      相关资源
      最近更新 更多