且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何滚动到文本区域中的光标位置?

更新时间:2023-12-05 11:10:40

从乔纳森·莱文(Jonathan Levine)的评论中,我意识到

From Jonathan Levine's comment, I realized that this answer works for me.

小提琴演示

JavaScript

$('#scroll-to-cursor').on('click', function() {    
    $('textarea').focus();
    $.event.trigger({ type : 'keypress' }); // works cross-browser

    // new KeyboardEvent('keypress'); // doesn't work in IE and Safari

    /* var evt = document.createEvent('KeyboardEvent');
    evt.initKeyEvent('keypress', true, true, null, false, false, false, false, 0, 32);
    $textarea.dispatchEvent(evt);

    evt = document.createEvent('KeyboardEvent');
    evt.initKeyEvent('keypress', true, true, null, false, false, false, false, 8, 0);
    $textarea.dispatchEvent(evt); */
});

/*
    To test:
    1) Click somewhere in the textarea to place cursor
    2) Scroll away so cursor isn't visible
    3) Click "Scroll to Cursor" button
*/

说明

当用户按下一个键时,浏览器会执行两件事:

When the user presses a key, the browser does two things:

  1. 将键放置在光标之后的位置.
  2. 滚动到该位置.

此解决方案仅模拟了此操作(无需实际输入任何文本).

This solution just simulates that (without actually entering any text).

旧解决方案不符合标准.已弃用 initKeyEvent .此更新仅使用 KeyboardEvent() 构造函数,兼容并且可以在除IE(Safari是一个问号)之外的所有浏览器中使用.

The old solution isn't standards compliant. initKeyEvent is deprecated. The update only uses the KeyboardEvent() constructor, which is compliant and works in all browsers except IE (Safari is a question mark).

使用$.event.trigger({ type : 'keypress' });代替new KeyboardEvent()同样有效,并且在所有浏览器中都可以使用.

Edit 2: Using $.event.trigger({ type : 'keypress' }); instead of new KeyboardEvent() works just as well, and works in all browsers.