0

虽然我已经得到了答案,但我会在这个问题上开始小额赏金。由于答案是不可能的,我正在寻找替代解决方案或其他一些建议。

我正在使用 HTML designMode 制作一个非常定制的编辑器。在一种情况下,我希望在按下实际键一次时完成两次按键的默认操作。在这种情况下,我说的是 DOWN 键(keyCode 40)。按下它时,我想跳过一行,将光标 ( |) 放在下一行。喜欢:

First li|ne
Second line
The third line

按下向下箭头键后:

First line
Second line
The third| line

我曾尝试以编程方式设置按键事件,让它们由 JavaScript 触发,但这不会发生移动光标。关于如何做到这一点的任何想法?

4

2 回答 2

2

你将无法以明智的方式做到这一点。在非 IE 浏览器中以编程方式移动插入符号的唯一方法是使用浏览器的Selection对象,该对象没有模拟向下箭头按键的机制。

于 2010-07-30T14:55:02.317 回答
0

You could do it with a combination of a few techniques. The first would be a function to move the cursor to an arbitrary position in a text area:

function setCaretPosition(elemId, caretPos) {
    var elem = document.getElementById(elemId);

    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}

The above code is from this blog post, which I had to use the google cache to view. Next you'd need to find the current cursor position in the textarea.

Finally, using the current cursor position, you could get the indexOf() the carriage returns in relation to your cursor position and use that to move your cursor down 2 lines.

Pretty it ain't, but it should work.

于 2010-07-30T15:11:36.250 回答