拖放时如何使textarea的光标移动到突出显示的文本的末尾?

时间:2019-11-09 07:32:40

标签: javascript html css

当我将图像拖放到文本区域时,文本将突出显示。
有没有办法使文本区域的光标移动到突出显示的文本的末尾?

document.querySelectorAll('.emoteImage').forEach((emoteImage) => {
  emoteImage.addEventListener('dragstart', (event) => {
    event.dataTransfer.setData('text', emoteImage.alt);
    event.effectAllowed = "copy";
  });
});
img {
  width: 100px;
}
<div class="emote">
<img src="https://images.duckduckgo.com/iu/?u=http%3A%2F%2Ficons.iconarchive.com%2Ficons%2Fpaomedia%2Fsmall-n-flat%2F512%2Fcat-icon.png&f=1" alt="emote1" title="emote1" class="emoteImage">
</div>


<textarea></textarea>

1 个答案:

答案 0 :(得分:1)

我添加了一个“ dragEnd”事件,将光标移动到突出显示的文本的末尾。 希望对您有所帮助:)

var element = document.getElementById("textArea");

document.querySelectorAll('.emoteImage').forEach((emoteImage) => {
  emoteImage.addEventListener('dragstart', (event) => {
    event.dataTransfer.setData('text', emoteImage.alt);
    event.effectAllowed = "copy";


});

emoteImage.addEventListener( 'dragend', function( event ) {
    var end = element.selectionEnd ;
    element.focus();
    element.setSelectionRange(end,end);
});

});
img {
  width: 100px;
}
<div class="emote">
<img src="https://images.duckduckgo.com/iu/?u=http%3A%2F%2Ficons.iconarchive.com%2Ficons%2Fpaomedia%2Fsmall-n-flat%2F512%2Fcat-icon.png&f=1" alt="emote1" title="emote1" class="emoteImage">
</div>


<textarea id="textArea" ></textarea>