document.selection.createRange()在chrome和safari中不起作用 [英] document.selection.createRange() not working in chrome and safari

查看:420
本文介绍了document.selection.createRange()在chrome和safari中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用文本模式作为多行选项的文本框,它在IE中工作正常,Chrome和Safari浏览器中出现Mozilla问题.示例代码如下

I am using a textbox with textmode as multiline option its working fine in IE,Mozilla problem occurs in Chrome and safari. Sample code folows

<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();     
}}

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

in chrome it gives me an error as "Cannot read property 'selection' of undefined"

推荐答案

非IE(不包括IE9)浏览器中(请参见注释),使用 window.getSelection 进行获取选择对象.在IE中9,原始代码应该可以使用.

In non IE (excluding IE9) browsers (see comments), use window.getSelection to get the selection object. In IE < 9, original code should work.

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();     
    }
}

通常,由于浏览器支持差异很大,因此使用 selection ranges 进行操作非常棘手.

In general, working with selection and ranges is very tricky as browser supports varies so much.

这是一本很好的参考书,列出了浏览器支持(以及什么代码在哪里工作)以及在相应浏览器中工作的示例代码:

Here's an excellent reference which lists out browser support (and what code works where) and sample code that works in corresponding browsers: http://help.dottoro.com/ljefwsqm.php

这篇关于document.selection.createRange()在chrome和safari中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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