javascript - 通过拖动移动动态创建的 DIV

标签 javascript jquery html draggable

我使用 JavaScript 动态创建 div 元素,每个 div 中还有一个移动图标,用户可以使用它来拖动/移动 div,这是我的 div 创建代码:

            var _body = document.getElementsByTagName('body')[0];
        var _div = document.createElement('div');
        _div.style.width = "250px";
        _div.style.height = "150px";
        _div.style.position = "relative";
        _div.id = "div" + count.toString();

        var imgMove = document.createElement("img");
        imgMove.setAttribute("src", "boxmove.png");
        _div.appendChild(imgMove);

当用户拖动移动图标时,如何使用 JQuery Draggable() 函数移动我的 div,还有其他解决方案吗?

最佳答案

handle选项设置为img,这意味着图像将用作拖动 handle 。

_body.appendChild(_div);
$(_div).draggable({ handle: "img" });

handle 选项是一个选择器,用于定位容器内的元素,因此您可以通过为图像指定一个类名来更具体,如果 div 中有多个图像,则需要该类名,但只想要某个图像作为拖动处理程序。

来自docs

handle

If specified, restricts dragging from starting unless the mousedown occurs on the specified element(s). Only elements that descend from the draggable element are permitted.

关于javascript - 通过拖动移动动态创建的 DIV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19763317/

相关文章:

javascript - Laravel 站点不在外部 javascript 文件中使用 Ajax

javascript - Angular 未捕获对象错误

javascript - 通过 GetElementsbyClass 内的标签在 GetElementbyID 嵌套的 dom 元素内获取元素

javascript - 使侧面菜单具有动态列

javascript - Jquery,打印json值出现的次数

HTML、CSS : Cannot reposition my dropdown list

javascript - 为什么表单值不显示?

javascript - 2048 : Strange behaviour of reduceRight in map with lodash/fp

javascript - 同一分页符上有 2 个脚本

javascript - jQuery 仅在父 li 上隐藏/显示