代码之家  ›  专栏  ›  技术社区  ›  avsej

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

  •  66
  • avsej  · 技术社区  · 15 年前

    我需要将插入符号移到结尾 contenteditable Gmail notes小部件上的节点。

    我读过StackOverflow上的线程,但这些解决方案是基于使用输入的,不能与 内容可编辑

    5 回复  |  直到 10 年前
        1
  •  0
  •   Dharman Bryan    4 年前

    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);