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

document.selection.createRange() not working in chrome and safari

本文关键字:safari 工作 chrome selection createRange document      更新时间:2023-09-26

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

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

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

通常,使用selectionranges是非常棘手的,因为浏览器支持的差异很大。

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

在文档中获取选定文本时存在许多缺点,主要与文本是否在表单控件中被选中或作为其他元素的文本有关。试试这样一个函数:

function checkForSelectedText(e) {
  var e = e || window.event;
  var el = e.target || e.srcElement;
  var tagName = el.tagName && el.tagName.toLowerCase();
  var t;
  var d = document;
  // Try DOM 2 Range - for most browsers, including IE 6+
  // However, doesn't get text selected inside form controls
  // that allow selection of text content (input type text, 
  // textarea)
  if (d && d.selection && d.selection.createRange) {
    t = d.selection.createRange().text;
  // Otherwise try HTML5 - note that getSelection returns
  // a string with extra properties. This may also get
  // text within input and textarea
  } else if (d.getSelection) {
    t = d.getSelection();
  }
  // If didn't get any text, see if event was inside
  // inupt@type=text or textarea and look for text
  if (t == '') {
    if (tagName == 'textarea' || 
       (tagName == 'input' && el.type == 'text')) {
     // Check selectionStart/End as otherwise if no text
     // selected, IE returns entire text of element
     if (typeof el.selectionStart == 'number' && 
         el.selectionStart != el.selectionEnd) {
        t = el.value.substring(el.selectionStart, el.selectionEnd)
     }
    }
  }
  return t;
}

我会用JQuery来做同样的事情,因为它是跨浏览器的,你写的是更抽象的java脚本,而不是你目前写的本地浏览器特定的。