开发者

HTML designMode, move cursor programmatically using default keypress handlers

开发者 https://www.devze.com 2023-01-09 08:41 出处:网络
Although I already got an answer, I\'ll start a small bounty on this one. As the answer is that it is impossible, I\'m searching for an alternative solution or some other suggestion.

Although I already got an answer, I'll start a small bounty on this one. As the answer is that it is impossible, I'm searching for an alternative solution or some other suggestion.

I'm making a very customized editor using the HTML designMode. In one situation, I want the default action of a keypress be accomplished twice when pressing the actual key once. In this case, I am talking about the DOWN key (keyCode 40). When pressing that, I want to skip one line, putting the cursor (|) on the next. Like:

First li|ne
Second line
The third line

After pressing the down arrow key:

开发者_JAVA技巧First line
Second line
The third| line

I have tried setting up keypress events programmatically, having them trigged by JavaScript, but that does not happen to move the cursor. Any ideas on how to do this?


You won't be able to do this in a sensible way. The only way to move the caret programmatically in non-IE browsers is by using the browser's Selection object, which has no mechanism for emulating a down arrow keypress.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号