我正在使用一些 JavaScript 将光标放置在可编辑段落和文本区域元素中的文本末尾。
可以在以下位置查看我的实际代码示例:Demo of my code
我发现奇怪的是,在 Chrome 中,单击按钮将光标位置设置在文本区域末尾会失败,但在最新的 FireFox 中,单击同一按钮会将光标放置在文本区域的开头。
问题
JavaScript 代码出了什么问题,在 Chrome 和 FireFox 上表现不一致?
相同的演示代码如下。
<button onclick="placeCursorAtEndofTextArea(); return false;">Place cursor at end of text area</button>
<button onclick="placeCursorAtEndofParagraph(); return false;">Place cursor at end of paragraph</button>
<br>
<br>
<textarea id="txtDescription" rows="10" cols="50">I am some text. I am some text. I am some text. I am some text.</textarea>
<br>
<br>
<p contentEditable>foo bar </p>
<style>
p {
border:1px solid green;
}
textarea {
border: 1px solid red;
}
</style>
<script>
function placeCaretAtEnd(el) {
el.focus();
if (typeof window.getSelection != "undefined"
&& typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}
function placeCursorAtEndofTextArea() {
placeCaretAtEnd( document.querySelector('#txtDescription'))
}
function placeCursorAtEndofParagraph() {
placeCaretAtEnd( document.querySelector('p'))
}
</script>
最佳答案
简而言之,这是因为 textarea
和 contentEditable
使用不同的选择模型。
我将其用于现代浏览器和 IE9+
function placeCaretAtEnd(el) {
if (el.value) {
// for textarea
el.focus();
el.setSelectionRange(el.value.length, el.value.length);
}
else {
// contentEditable
range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
}
function placeCursorAtEndofTextArea() {
placeCaretAtEnd(document.querySelector('#txtDescription'))
}
function placeCursorAtEndofParagraph() {
placeCaretAtEnd(document.querySelector('p'))
}
p {border: 1px solid green;}
textarea {border: 1px solid red;}
textarea:focus::-webkit-input-placeholder{color: transparent;}
textarea:focus::-webkit-textarea-placeholder {content: "";}
<button onclick="placeCursorAtEndofTextArea(); return false;">Place cursor at end of text area</button>
<button onclick="placeCursorAtEndofParagraph(); return false;">Place cursor at end of paragraph</button>
<br><br>
<textarea id="txtDescription" rows="10" cols="50">I am some text. I am some text. I am some text. I am some text.</textarea>
<br><br>
<p contentEditable>foo bar </p>
关于javascript - 为什么光标仅在 FireFox 中不位于末尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53568493/