简体   繁体   English

在悬停/悬停时获得插入符位置

[英]Getting the caret position on hover/dragover

I am trying to get the caret position of the (rich)textbox I am dragging some text over. 我正在尝试将(文本)文本框的插入位置 拖到一些文本上。

The reason behind this is that I need to add some extra characters to the dropped text in my textbox, so I needed to prevent the default drop behavior. 这背后的原因是,我需要在文本框中的拖放文本中添加一些额外的字符,因此需要防止默认的拖放行为。

function drop(event) {
    event.preventDefault();
    var data = event.dataTransfer.getData("text");
    var placeholder = document.createTextNode("[%" + data + "%]");
    event.target.appendChild(placeholder);
}

With event.target.appendChild the content is placed at the end of the textbox, so there should be a way to figure out what the position of the caret is when dragging/hovering. 使用event.target.appendChild将内容放置在文本框的末尾,因此应该有一种方法可以确定拖动/悬停时插入标记的位置。

This is where I'd like my text to be dropped: 这是我希望删除文本的地方:

在此处输入图片说明

Instead, it's added to the end of my input content: 而是将其添加到我的输入内容的末尾:

在此处输入图片说明

Instead of manipulating the drop -event, I got it working by manipulating the dragstart -event. 我没有操纵drop -event,而是通过操纵dragstart -event使它起作用。

 var btn = document.getElementById("foo"); btn.onclick = function(event) { event.preventDefault(); }; btn.ondragstart = function(event) { event.dataTransfer.setData("text/plain", "[%" + event.srcElement.innerHTML + "%]"); }; 
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" /> <span draggable="true" id="foo" class="btn btn-primary">Foo</span> <input type="text" /> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM