У меня есть текстовая область, в которую пользователи могут вводить текст. Когда они выбирают текст, я хотел бы получить строку и столбец выделенного текста (или курсора), если они не выделяют какой-либо текст.
В приведенном ниже примере используется событие on focus.Следует использовать событие изменения курсора или изменения выбора.
document.getElementById('textarea').onselectionchange = onFocusHandler;
document.getElementById('textarea').onselect = onFocusHandler;
document.getElementById('textarea').onfocus = onFocusHandler;
document.getElementById('textarea').onmouseup = onFocusHandler;
document.getElementById('textarea').onselectionstart = onFocusHandler;
function onFocusHandler(event){
var textarea = document.getElementById('textarea');
var value = textarea.value;
var anchorPosition = 0;
var activePosition = 0;
var userSelection;
var range;
console.log(event.type);
if (window.getSelection) {
//console.log("1");
userSelection = window.getSelection();
//console.log(userSelection);
//range = userSelection.getRangeAt(0);
//console.log(range);
}
else if (document.selection) {
userSelection = document.selection.createRange();
}
console.log("Cursor:" + userSelection.anchorOffset);
return;
if (userSelection.getRangeAt) {
//range = userSelection.getRangeAt(0);
}
else {
range = document.createRange();
range.setStart(userSelection.anchorNode, userSelection.anchorOffset);
range.setEnd(userSelection.focusNode, userSelection.focusOffset);
}
//console.log(range);
textarea.focus();
if (textarea.setSelectionRange) {
textarea.setSelectionRange(anchorPosition, activePosition);
}
else {
var range = textarea.createTextRange();
range.collapse(true);
range.moveEnd('character', activePosition);
range.moveStart('character', anchorPosition);
range.select();
}
};
<textarea id="textarea" style="width:100%;height:100px">Hello world.
It's a nice day.
Go outside and get some sun.
</textarea>
<span id="row">Row</span>