setSelectionRange 跨浏览器的行为方式不一样?
我在另一个问题上发现了这一点:
setCaretToPos = function(input, selectionStart, selectionEnd){
if(input.setSelectionRange){
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}else if(input.createTextRange){
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
};
setCaretToPos(8, 12);
它应该从第 8 个字符和第 12 个字符之间的文本区域中选择文本。
它适用于 Firefox 和 Chrome,但在 Opera 中我得到了错误的选择。偏移量向后移动两个字符
有什么问题吗?
It seems it has something to do with new lines:
\n
because the selection is correct if the text doesn't contain new line character.I found this on a different question:
setCaretToPos = function(input, selectionStart, selectionEnd){
if(input.setSelectionRange){
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}else if(input.createTextRange){
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
};
setCaretToPos(8, 12);
It should select text from a text area between the 8th character and 12th character.
It works in Firefox and Chrome, but in Opera I get the wrong selection. Offset moves two characters behind
What's wrong with it?
It seems it has something to do with new lines:
\n
because the selection is correct if the text doesn't contain new line character.如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 Opera 和 IE 中,换行符是文本区域中的两个字符(CRLF 或
\r\n
),而在其他浏览器中是一个字符(\n
)。你需要对此进行调整。这是一个执行此操作的函数,在所有浏览器中将换行符视为单个字符。现场演示: http://jsfiddle.net/DqtVK/1/
代码:
New lines are two characters (CRLF, or
\r\n
) in textareas in Opera and IE and one character (\n
) in other browsers. You'll need to adjust for that. Here's a function to do that, treating line breaks as a single character in all browsers.Live demo: http://jsfiddle.net/DqtVK/1/
Code: