如何处理 textarea
的 selectionchange
事件?
我尝试过:
$('#editor').on('selectionchange', function () {
console.log(arguments);
});
不工作。我错了吗?
最佳答案
当 document
上的当前文本选择发生更改时,会触发 selectionchange
事件。仅当目标对象是文档时此事件才有效。 HTML 输入元素
和 HTML 文本区域元素
的此事件仅在 Firefox 52 及更高版本中受支持。请参阅Browser compatibility .
那么,您是否需要在textarea
中获取所选文本?您可能需要 selectionStart
和 selectionEnd
(Internet Explorer 中不存在,但适用于 Firefox 和 Chrome)。请参阅下面的示例:
示例:
$( document ).on( 'mouseup', 'body', function() {
console.clear();
if ( getSelectionText() ) console.log( getSelectionText() )
});
function getSelectionText() {
if ( window.getSelection ) {
try {
var tarea = $( 'textarea' ).get(0);
return ( tarea.selectionStart != tarea.selectionEnd ) ? 'The event triggered. You select "' + tarea.value.substring( tarea.selectionStart, tarea.selectionEnd ) + '"' : '';
} catch ( e ) {
console.log( 'Cant get selection text' )
}
}
// For IE
if ( document.selection && document.selection.type != 'Control' )
return document.selection.createRange().text;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>Salam textarea</textarea>
关于javascript - jQuery 的文本区域选择更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50771169/