需要将光标位置设置为contentEditable div的末尾,与选择和范围对象一起发出问题 [英] Need to set cursor position to the end of a contentEditable div, issue with selection and range objects

查看:161
本文介绍了需要将光标位置设置为contentEditable div的末尾,与选择和范围对象一起发出问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我暂时忘记了跨浏览器兼容性,我只想让它发挥作用。
我正在做的是尝试修改一个脚本(你可能不需要知道这个)位于 typegreek.com 基本脚本位于此处。基本上它的作用是当你输入字符时,它会将你输入的字符转换成希腊字符并将其打印到屏幕上。我想要做的是让它在contentEditable div上工作(它只适用于Textareas)

I'm forgetting about cross-browser compatibility for the moment, I just want this to work. What I'm doing is trying to modify a script (and you probably don't need to know this) located at typegreek.com The basic script is found here. Basically what it does is when you type in characters, it converts the character your are typing into greek characters and prints it onto the screen. What I'm trying to do is to get it to work on contentEditable div's (It only works for Textareas)

我的问题是这一个功能:用户输入一个键,它被转换为希腊键,然后转到一个函数,它通过一些if进行排序,最后它在哪里可以添加div支持。这是我到目前为止所拥有的,

My issue is with this one function: The user types a key, it get's converted to a greek key, and goes to a function, it gets sorted through some if's, and where it ends up is where I can add div support. Here is what I have so far,

myField是div,myValue是希腊字符。

myField is the div, myValue is the greek character.

//Get selection object...
var userSelection
 if (window.getSelection) {userSelection = window.getSelection();}
 else if (document.selection) {userSelection = document.selection.createRange();}

//Now get the cursor position information...
var startPos = userSelection.anchorOffset;
var endPos = userSelection.focusOffset;
var cursorPos = endPos;

//Needed later when reinserting the cursor...
var rangeObj = userSelection.getRangeAt(0) 
var container = rangeObj.startContainer

//Now take the content from pos 0 -> cursor, add in myValue, then insert everything after myValue to the end of the line.
myField.textContent = myField.textContent.substring(0, startPos) + myValue + myField.textContent.substring(endPos, myField.textContent.length);

//Now the issue is, this updates the string, and returns the cursor to the beginning of the div. 
//so that at the next keypress, the character is inserted into the beginning of the div.
//So we need to reinsert the cursor where it was.

//Re-evaluate the cursor position, taking into account the added character.
  var cursorPos = endPos + myValue.length;

  //Set the caracter position.
  rangeObj.setStart(container,cursorPos) 

现在,只有我才有效不要输入超过原始文本的大小。假设我手中有30个字符。如果我键入超过30,它会添加字符31,但将光标放回30.我可以在pos.31键入字符32,然后在pos.32键入字符33,但如果我尝试将字符34放入,则添加字符,并将光标设置为32.问题是,如果cursorPos大于范围中定义的值,则添加新字符的功能会搞定。任何想法?

Now, this works only as long as I don't type more than the size of the original text. Say I had 30 characters in the div before hand. If I type more than that 30, it adds character 31, but places the cursor back at 30. I can type character 32 at pos.31, then character 33 at pos.32, but if I try to put character 34 in, it adds the character, and sets the cursor back at 32. The issue is that the function for adding the new character screws up if cursorPos is greater than what is defined in the range. Any ideas?

推荐答案

在一个可信的div中比在textarea中更容易做这个跨浏览器。以下假设您的contenteditable div的id为greek。

It's easier to do this cross-browser in a contenteditable div than a textarea. The following assumes your contenteditable div has an id of "greek".

var greekChars = {
    "a": "\u03b1"
    // Add character mappings here
};

function convertCharToGreek(charStr) {
    return greekChars[charStr] || "[Greek]";
}

function insertTextAtCursor(text) {
    var sel, range, textNode;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
            textNode = document.createTextNode(text);
            range.insertNode(textNode);

            // Move caret to the end of the newly inserted text node
            range.setStart(textNode, textNode.length);
            range.setEnd(textNode, textNode.length);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    } else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        range.pasteHTML(text);
    }
}

var div = document.getElementById("greek");

div.onkeypress = function(evt) {
    evt = evt || window.event;
    var charCode = (typeof evt.which == "undefined") ? evt.keyCode : evt.which;
    if (charCode) {
        var charStr = String.fromCharCode(charCode);
        var greek = convertCharToGreek(charStr);
        insertTextAtCursor(greek);
        return false;
    }
}

这篇关于需要将光标位置设置为contentEditable div的末尾,与选择和范围对象一起发出问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆