需要将光标位置设置到 contentEditable div 的末尾,选择和范围对象出现问题

发布于 2024-09-03 17:09:07 字数 1858 浏览 9 评论 0原文

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

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

myField 是 div,myValue 是希腊字符。

//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) 

现在,只有当我输入的内容不超过原始文本的大小时,这才有效。假设我事先在 div 中有 30 个字符。如果我输入的数字超过 30,它会添加字符 31,但会将光标放回到 30。我可以在 pos.31 处输入字符 32,然后在 pos.32 处输入字符 33,但如果我尝试输入字符 34,它会添加字符,并将光标设置回 32。问题是,如果cursorPos 大于范围中定义的值,添加新字符的函数就会出错。有什么想法吗?

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)

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 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) 

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

念三年u 2024-09-10 17:09:07

在 contenteditable div 中执行此跨浏览器操作比在文本区域中更容易。以下假设您的 contenteditable div 的 id 为“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;
    }
}

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;
    }
}
红焚 2024-09-10 17:09:07

我认为您可能将起始偏移设置为超出结束偏移。

插入文本时,应先设置结束偏移,然后再设置起始偏移。

rangeObj.setEnd(container, cursorPos);
rangeObj.setStart(container,cursorPos);

I think you maybe setting the start offset beyond the end offset.

You should set the end offset first before the start offset when you are inserting text.

rangeObj.setEnd(container, cursorPos);
rangeObj.setStart(container,cursorPos);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文