在可信任的div中拖放dom元素

时间:2015-07-06 11:50:34

标签: jquery html contenteditable drag

我有以下html结构:

<div contenteditable="true">
     this is a <span class='gat'>draggable</span> text and i would like to <span class='gat'>drag it inside</span> the div parent.  
</div>

我希望span元素只能在父div dom中拖动。如果我想把第二个跨度移动到开头,我会得到:

<div contenteditable="true">
     <span class='gat'>drag it inside</span> this is a <span class='gat'>draggable</span> text and i would like to the div parent.  
</div>

我正在寻找与所有主流浏览器兼容的解决方案。 (我正在使用JQuery)。

编辑:以下是我需要的示例(无需点击之前拖动):http://jsfiddle.net/s82Ex/

2 个答案:

答案 0 :(得分:1)

使用jquery UI,这里是实现此目的的代码:

 <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
  <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
</script>
<style>
.parent{
    overflow: hidden;
    position: relative;
    width: 1000px;
    height: 1000px;
    border: 2px solid;
}


</style>


<div class="parent" contenteditable="true">
     this is a <span class='gat'>draggable</span> text and i would like to <span class='gat'>drag it inside</span> the div parent.  
</div>
<script>
$('.gat').draggable({ containment: "parent" });
</script>

有关详细参考,请查看此link

DEMO: http://jsfiddle.net/ishandemon/junq47q9/

DEMO2: http://jsfiddle.net/ishandemon/junq47q9/2/

答案 1 :(得分:0)

您可以使用range选择mousedown上的范围,然后它就像您可以拖动的所选文字一样。像这样:

    var gatSpans = document.getElementsByClassName('gat');

    for (var i = 0; i < gatSpans.length; i++) {
        gatSpans[i].onmousedown = function (e) {

            var sel = window.getSelection();
            var range = document.createRange();
            range.setStart(e.target, 0);
            range.setEnd(e.target, 1);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }

https://jsfiddle.net/6Lobg46a/3/

编辑:

要使用此方法多次使用它,使用委派事件会更容易,并且您必须设置dataTransfer以保持跨度拖动。像这样:

    $('div').on('mousedown', '.gat', function (e) {

        var sel = window.getSelection();
        var range = document.createRange();
        range.selectNode(e.target);
        sel.removeAllRanges();
        sel.addRange(range);

    });
    $('div')[0].ondragstart = function(e){

        e.dataTransfer.setData('text/html', '<span class="gat">'+e.dataTransfer.getData("text/plain")+'</span>')
    }

https://jsfiddle.net/6Lobg46a/6/