12
<div contenteditable="true" id="d">
<span>Text to edit</span>
</div>

$("#d").draggable();

我只能拖动这个 div 但我如何编辑它(比如双击可编辑属性变为活动状态,点击拖动变为活动状态)?

4

5 回答 5

20
$("#d").draggable()
  .click(function() {
    $(this).draggable({ disabled: false });
}).dblclick(function() {
    $(this).draggable({ disabled: true });
});
​​

演示

于 2012-04-25T14:13:08.747 回答
9
$("#d")
.draggable()
.click(function(){
    if ( $(this).is('.ui-draggable-dragging') ) {
        return;
    }
    $(this).draggable( "option", "disabled", true );
    $(this).attr('contenteditable','true');
})
.blur(function(){
    $(this).draggable( 'option', 'disabled', false);
    $(this).attr('contenteditable','false');
});

这是演示:http: //jsfiddle.net/UH9UE/222/

于 2013-02-19T07:42:37.233 回答
6

另一种选择是传递 .draggable({ handle: "handleDiv" }) ,它允许您一直保持可拖动以及允许内容可编辑的编辑。只需在内部创建两个 div 的可拖动 div:句柄和 contenteditable div。

API 文档

于 2013-01-31T16:25:27.967 回答
0

我发现跟随行为更加直观和流畅(无需双击)。

版本 1(最佳) http://jsfiddle.net/k1d9ftyu/

d.onmousedown = e => {
    d.contentEditable = false
}

d.ondragstart = e => {
    e.dataTransfer.setData('text', "XXX");
}

d.ondragend = () => {
    d.contentEditable = true
}

d.onmouseup = e => {
    d.contentEditable = true
    if (document.caretRangeFromPoint)
        range = document.caretRangeFromPoint(e.clientX, e.clientY)
    else {   // firefox
        var sel = window.getSelection()
        sel.collapse(e.rangeParent, e.rangeOffset)
    }
}
#d {
    background-color: #cfc;
    width: 200px;
}

#d[contenteditable=false] {
    cursor: grab;
}
<div contenteditable=true>
The green child div is contenteditable by default (as well as the parent div). The caret can run through both divs.
<div id="d" draggable=true contenteditable=true>Mousedown sets contenteditable=false, the div can be dragged. If not dragged after click, it becomes again contenteditable.</div>
The caret is positioned according to the last click.
</div>

版本 2

与版本 1 类似,但mouseenter需要再次单击才能正确定位插入符号:http: //jsfiddle.net/z8aojdg6

版本 3
默认为 原始版本contenteditable=false。由于focus()调用,插入符号被放置在行尾。因此,需要再次单击以重新定位插入符号(使用selectionand可能会对其进行改进range)。

d.onmouseup = () => {
  d.contentEditable = true
  d.focus()
}

d.onblur = () => {
  d.contentEditable = false
}
#d {
    background-color: #ccc;
    width: 130px;
    height: 90px;
}
#d:focus {
    outline: 2px solid blue;
}
<div id="d" draggable=true contenteditable=false>
  Edit me when focussed. Drag me when inactive.</div>

演示:http: //jsfiddle.net/rz28c0xe

于 2021-10-12T21:10:24.647 回答
-1
<div contenteditable="true" id="d">
<span>Text to edit</span>
</div>

$(function(){
$("#d").click(function() {
$("#d").draggable();      
});

$("#d").dblclick(function(){
see here for this functionality http://stackoverflow.com/questions/2441565/how-do-i-make-a-div-element-editable-like-a-textarea-when-i-click-it   
}); 
}); 

​</p>

于 2012-04-25T14:06:22.417 回答