jQuery on textarea selectionchange

哈米德·扎克里·米阿布

我该如何处理 a 的selectionchange事件textarea

我试过了:

$('#editor').on('selectionchange', function () {
   console.log(arguments);               
});

不工作。我错了吗?

卡维安 K。

selectionchange当 a 上的当前文本选择document更改时,将触发事件此事件仅在目标对象是document. 此事件HTML Input Element,并HTML Text Area Element只在Firefox 52及以上版本支持。请参阅浏览器兼容性

那么,您是否需要在textarea. 您可能会要求selectionStartselectionEnd(在 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>

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章