出于某种原因,当我处理 pasteEvent 时,myTextArea.selectionStart 工作得很好,但是当我处理放置事件时,它是错误的。如何将放置事件的目标光标位置放入文本区域?例如,我想知道用户是否在文本区域内容的开头或结尾拖放了一些文本。假设文本区域的值无法更改(如示例中所示)。为了方便起见,我在示例中使用了 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>
关于javascript - 处理drop事件时如何定位游标索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39151580/