gpt4 book ai didi

javascript - 如何将光标移动到 contenteditable 实体的末尾

转载 作者:行者123 更新时间:2023-11-28 19:15:11 26 4
gpt4 key购买 nike

我需要将插入符号移动到 contenteditable 节点的末尾,就像在 Gmail 笔记小部件上一样。

我阅读了 StackOverflow 上的帖子,但这些解决方案是基于使用输入的,它们不适用于 contenteditable 元素。

最佳答案

Geowa4 的解决方案适用于 textarea,但不适用于 contenteditable 元素。

此解决方案用于将插入符号移动到 contenteditable 元素的末尾。它应该适用于所有支持 contenteditable 的浏览器。

function setEndOfContenteditable(contentEditableElement)
{
var range,selection;
if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
{
range = document.createRange();//Create a range (a range is a like the selection but invisible)
range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
selection = window.getSelection();//get the selection object (allows you to change selection)
selection.removeAllRanges();//remove any selections already made
selection.addRange(range);//make the range you have just created the visible selection
}
else if(document.selection)//IE 8 and lower
{
range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
range.select();//Select the range (make it the visible selection
}
}

它可以被类似于以下的代码使用:

elem = document.getElementById('txt1');//This is the element that you want to move the caret to the end of
setEndOfContenteditable(elem);

关于javascript - 如何将光标移动到 contenteditable 实体的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58497026/

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