<div contenteditable="true" id="d">
<span>Text to edit</span>
</div>
$("#d").draggable();
我只能拖动这个 div 但我如何编辑它(比如双击可编辑属性变为活动状态,点击拖动变为活动状态)?
$("#d").draggable()
.click(function() {
$(this).draggable({ disabled: false });
}).dblclick(function() {
$(this).draggable({ disabled: true });
});
$("#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/。
另一种选择是传递 .draggable({ handle: "handleDiv" }) ,它允许您一直保持可拖动以及允许内容可编辑的编辑。只需在内部创建两个 div 的可拖动 div:句柄和 contenteditable div。
我发现跟随行为更加直观和流畅(无需双击)。
版本 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()
调用,插入符号被放置在行尾。因此,需要再次单击以重新定位插入符号(使用selection
and可能会对其进行改进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
<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>