简体   繁体   English

Javascript文字范围直至插入符号位置

[英]Javascript text range up to caret position

I am using IE 8 and I would like to create a text range in a contenteditable div which should include all text until caret position (known to me in the editableDiv). 我正在使用IE 8,我想在contenteditable div中创建一个文本范围,该范围应包括所有文本,直到插入符号的位置(在editableDiv中为我所知)。 So far I was able to select all text inside my the div: 到目前为止,我已经能够在div中选择所有文本:

 function myFunction(editableDiv, cursorPosition)
 {
    if (document.selection) {
       var range = document.body.createTextRange();
        range.moveToElementText(editableDiv);            
        range.collapse(false);
        range.select();
    }
 }

<div id="myDiv" runat="server" contenteditable="true">

But how can I create a text range that begins with the first character in the div and lasts up to caret position? 但是,如何创建一个以div中的第一个字符开始并持续到插入符号位置的文本范围? Thank you very much. 非常感谢你。

Use the setEndPoint() method of TextRange : 使用TextRangesetEndPoint()方法:

var caretRange = document.selection.createRange();
var preCaretRange = document.body.createTextRange();
preCaretRange.moveToElementText(editableDiv);
preCaretRange.setEndPoint("EndToStart", caretRange);

Obviously you'll need different code for non-IE browsers. 显然,对于非IE浏览器,您将需要不同的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM