[英]setSelectionRange not behaving the same way across browsers?
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. 它应该从第8个字符和第12个字符之间的文本区域中选择文本。
It works in Firefox and Chrome, but in Opera I get the wrong selection. 它适用于Firefox和Chrome,但在Opera中我选错了。 Offset moves two characters behind
偏移移动两个字符
What's wrong with it? 它出什么问题了?
\\n
because the selection is correct if the text doesn't contain new line character.
\\n
因为如果文本不包含换行符,则选择正确。
New lines are two characters (CRLF, or \\r\\n
) in textareas in Opera and IE and one character ( \\n
) in other browsers. 新行是Opera和IE中textareas中的两个字符(CRLF或
\\r\\n
)和其他浏览器中的一个字符( \\n
)。 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/ 现场演示: http : //jsfiddle.net/DqtVK/1/
Code: 码:
function adjustOffset(el, offset) {
var val = el.value, newOffset = offset;
if (val.indexOf("\r\n") > -1) {
var matches = val.replace(/\r\n/g, "\n").slice(0, offset).match(/\n/g);
newOffset += matches ? matches.length : 0;
}
return newOffset;
}
var setCaretToPos = function(input, selectionStart, selectionEnd){
input.focus();
if(input.setSelectionRange){
selectionStart = adjustOffset(input, selectionStart);
selectionEnd = adjustOffset(input, selectionEnd);
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();
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.