javascript – 如何在处理drop事件时定位游标索引?

出于某种原因,myTextArea.selectionStart在处理pasteEvent时工作得很好,但是当我处理drop事件时,它是错误的.如何将drop事件的目标光标位置放入文本区域?例如,我想知道用户是否在textarea的内容或结尾处拖放一些文本.假设文本区域的值不能改变(如示例中所示).为方便起见,我在我的例子中使用了jQuery;这不是问题的一部分.

编辑:可能不是很清楚.如果您运行代码片段(在聚焦文本区域之前),将文本拖放到文本区域的末尾,则会将放置位置报告为0而不是预期18.

$('#x').on('drop', function(event){
   $('#y').html(event.target.selectionStart);
   return false;
 });

$('#x').on('paste', function(event){
   $('#z').html(event.target.selectionStart);
   return false;
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Try drag/dropping this text before and after existing text, then try with copy/paste</div>
<textarea id="x">some existing text</textarea>
<div>The drop position was <span id="y"></span></div>
<div>The paste position was <span id="z"></span></div>

最佳答案 今晚我有点想法,如何破解你的问题.我目前的解决方案是:

您正在取消放置和粘贴事件,但我让它们发生了.之后我计算旧字符串和新字符串的区别,用这个,你可以得到改变的位置:)

适合您的情况.

let drop_event = 'drop';
let paste_event = 'paste';
let events = [drop_event, paste_event];
var old_val = $('#x').val();
var current_event = '';
var cursor_pos = 0;
var sel_len = 0;

// iterate through each event
$.each( events, function( key, value ) {
  $('#x').on(value, function(event){
    // saving old value and the current event
    old_value = $('#x').val();
    current_event = value;
  });
});


$('#x').on('input', function(event){
  // position, where the string change starts
  cursor_pos = event.target.selectionStart;
  if (current_event == drop_event){
    // drop events are eays
    $('#y').html(cursor_pos);
  } else {
    // substract the length of change
    $('#z').html(cursor_pos - diff_string($('#x').val(), old_val));
  }
  // set old string value
  $('#x').val(old_val);
});

/*
 * Calculates the difference between two strings,
 * iff one string is substring of the other string
 * @param a first string
 * @param b second string
 * @return differnce as int
 */
function diff_string(a, b){
  var len = a.length > b.length ? b.length : a.length;
  var index = 0;
  while (a.charAt(index) == b.charAt(index))
    index += 1;
  a = a.substr(index);
  b = b.substr(index);
  var diff = a.length > b.length ? a.indexOf(b) : b.indexOf(a);
  diff = diff == 0 ? a.length + b.length : diff;
  return diff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Try drag/dropping this text before and after existing text, then try with copy/paste</div>
<textarea id="x">123456789 some existing text</textarea>
<div>The drop position was <span id="y"></span></div>
<div>The paste position was <span id="z"></span></div>
点赞