[英]How can I get the "drop caret position" from contenteditable?
If one drags an element from within a contenteditable
the browser usually shows such an "intermediate caret" as can be seen in the image below:如果从
contenteditable
拖动一个元素,浏览器通常会显示这样一个“中间插入符号”,如下图所示:
I am looking for a simple and reliable solution to drag an element from within a contenteditable
by sending the elements ID as transfer data via drag and drop.我正在寻找一种简单可靠的解决方案,通过拖放将元素 ID 作为传输数据发送,从而从
contenteditable
拖动元素。 Then, in the ondrop
method I intend to place the draggable
at the exact position where this "intermediate caret" is currently at.然后,在
ondrop
方法中,我打算将draggable
放置在此“中间插入符”当前所在的确切位置。
The question is: Will I be able to get this information from all the browsers?问题是:我能从所有浏览器中获取这些信息吗?
I do have a base ( JSFiddle ) but that's far from being useful for me at the moment.我确实有一个基础( JSFiddle ),但目前这对我来说远没有用。
PS: I am not using jQuery or any other libraries. PS:我没有使用 jQuery 或任何其他库。
Check out document.caretRangeFromPoint
and e.rangeParent, e.rangeOffset
.查看
document.caretRangeFromPoint
和e.rangeParent, e.rangeOffset
。
Here is a demo https://jsfiddle.net/znghofxt这是一个演示https://jsfiddle.net/znghofxt
function dragElement(e) { e.dataTransfer.setData('text/plain', e.target.id); } function drop(e) { e.preventDefault(); var id = e.dataTransfer.getData("text/plain"); if (document.caretRangeFromPoint) { // edge, chrome, android range = document.caretRangeFromPoint(e.clientX, e.clientY) } else { // firefox var pos = [e.rangeParent, e.rangeOffset] range = document.createRange() range.setStart(...pos); range.setEnd(...pos); } range.insertNode(document.getElementById(id)); }
.fancy { background-color: #123456; color: white; border-radius: 8px 8px 8px 8px; cursor:pointer; display: inline-block; padding: 20px; } .fancy-img { cursor:pointer; display: inline-block; }
<div contenteditable="true" ondrop="drop(event)"> More blah about <a id="dragme" href="http://www.google.com" class="fancy" contenteditable="false" ondragstart="dragElement(event)"> :( </a> Sparta! </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.