我正在使用带有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中的它给我一个错误,因为“无法读取未定义的属性'选择”
答案 0 :(得分:5)
在非IE(IE9除外)浏览器(请参阅注释)中,使用window.getSelection
获取选择对象。在IE&lt; 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();
}
}
一般情况下,使用selection
和ranges
非常棘手,因为浏览器支持的变化太大了。
这是一个很好的参考,列出了浏览器支持(以及代码在哪里工作)以及在相应浏览器中运行的示例代码:http://help.dottoro.com/ljefwsqm.php
答案 1 :(得分:1)
在文档中获取选定文本时存在许多缺陷,主要与是否在表单控件中选择文本或与某些其他元素的文本相关。尝试执行以下操作的功能:
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;
}
答案 2 :(得分:0)
我会使用JQuery来做同样的事情,因为它是跨浏览器,你编写了更抽象的java脚本,而不是你到目前为止写的本机浏览器。