document.selection.createRange()在chrome和safari中不起作用

Mat*_*aul 0 javascript c# asp.net

我正在使用带有textmode的文本框作为多行选项,它在IE中运行良好,Mozilla问题出现在Chrome和Safari中.示例代码如下

<asp:TextBox ID="txtRootDescription" onpaste="DoPaste(this);" Width="600px" Rows="10" Columns="72" MaxLength="500" TextMode="MultiLine" runat="server"></asp:TextBox>

function DoPaste(control) {
maxLength = control.attributes["maxlength"].value;   
if (maxLength) {        
    var oTR = control.document.selection.createRange();     
}}
Run Code Online (Sandbox Code Playgroud)

在chrome中它给我一个错误,因为"无法读取未定义的属性'选择'

Mrc*_*ief 5

非IE(IE9除外)浏览器中(参见注释),用于window.getSelection获取选择对象.在IE <9中,原始代码应该有效.

function GetSelection () {
    if (window.getSelection) {  // all browsers, except IE before version 9
        var selectionRange = window.getSelection ();                                        
        return selectionRange.toString();
    } 
    else {
        if (document.selection.type == 'None') {
            return "";
        }
        else {
            var textRange = document.selection.createRange ();
            return textRange.text;
        }
    }
}

function DoPaste(control) {
    maxLength = control.attributes["maxlength"].value;   
    if (maxLength) {        
        var oTR = GetSelection();     
    }
}
Run Code Online (Sandbox Code Playgroud)

一般来说,随着浏览器支持的变化,使用selection并且ranges非常棘手.

这是一个很好的参考,列出了浏览器支持(以及代码在哪里工作)和在相应浏览器中工作的示例代码:http://help.dottoro.com/ljefwsqm.php