gpt4 book ai didi

javascript - placeCaretAtEnd 似乎无法在 Firefox 中工作

转载 作者:行者123 更新时间:2023-11-28 00:55:58 25 4
gpt4 key购买 nike

我有一个内容可编辑的 DIV,其中包含一个带有文本的 P 标签,并使用 placeCaretAtEnd 将插入符号定位在 P 标签内内容的末尾。这似乎适用于除 Firefox (v32.0.3) 之外的所有浏览器。此时,插入符号似乎消失了。

据我所知,placeCaretAtEnd JS 函数应该与 Firefox 完全兼容。知道为什么这在这种情况下不起作用吗?

工作示例位于:http://jsfiddle.net/0ktff3zj/1/

<input id=button type=button value="Caret to end">
<div contenteditable=true>
<p id="paragraph">Sample text. Sample text.</p>
</div>

<script>
$('#button').bind('click', function() {
placeCaretAtEnd(document.getElementById('paragraph'))
});

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

最佳答案

我通过将光标放在 contenteditable div 中,然后使用 placeCaratAtEnd 函数移动它来解决这个问题。

首先,我给了 div 一个 id,这样就不会混淆。

$('#button').bind('click', function() {
$('div#id').focus();
placeCaretAtEnd(document.getElementById('paragraph'))
});

我一直在搜索,虽然我知道这有点黑客,但这是一个解决方案。

关于javascript - placeCaretAtEnd 似乎无法在 Firefox 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26220246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com