简体   繁体   中英

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.

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.

 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" /> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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