Как переместить курсор в конец contenteditable лица

мне нужно переместить каретку до конца contenteditable узел, как на Gmail notes widget.

Я читаю потоки в StackOverflow, но эти решения основаны на использовании входных данных, и они не работают с contenteditable элементы.

4 ответов


есть еще одна проблема.

на Нико Горитрешение работает, если contenteditable div не содержит других многолинейных элементов.

например, если div содержит другие divs, а эти другие divs содержат другие вещи внутри, могут возникнуть некоторые проблемы.

чтобы решить их, я организовал следующее решение, которое является улучшением Нико'ы один:

//Namespace management idea from http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/
(function( cursorManager ) {

    //From: http://www.w3.org/TR/html-markup/syntax.html#syntax-elements
    var voidNodeTags = ['AREA', 'BASE', 'BR', 'COL', 'EMBED', 'HR', 'IMG', 'INPUT', 'KEYGEN', 'LINK', 'MENUITEM', 'META', 'PARAM', 'SOURCE', 'TRACK', 'WBR', 'BASEFONT', 'BGSOUND', 'FRAME', 'ISINDEX'];

    //From: https://stackoverflow.com/questions/237104/array-containsobj-in-javascript
    Array.prototype.contains = function(obj) {
        var i = this.length;
        while (i--) {
            if (this[i] === obj) {
                return true;
            }
        }
        return false;
    }

    //Basic idea from: https://stackoverflow.com/questions/19790442/test-if-an-element-can-contain-text
    function canContainText(node) {
        if(node.nodeType == 1) { //is an element node
            return !voidNodeTags.contains(node.nodeName);
        } else { //is not an element node
            return false;
        }
    };

    function getLastChildElement(el){
        var lc = el.lastChild;
        while(lc && lc.nodeType != 1) {
            if(lc.previousSibling)
                lc = lc.previousSibling;
            else
                break;
        }
        return lc;
    }

    //Based on Nico Burns's answer
    cursorManager.setEndOfContenteditable = function(contentEditableElement)
    {

        while(getLastChildElement(contentEditableElement) &&
              canContainText(getLastChildElement(contentEditableElement))) {
            contentEditableElement = getLastChildElement(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
        }
    }

}( window.cursorManager = window.cursorManager || {}));

использование:

var editableDiv = document.getElementById("my_contentEditableDiv");
cursorManager.setEndOfContenteditable(editableDiv);

таким образом, курсор, безусловно, расположен в конце последнего элемента, в конечном итоге вложенного.

правка #1: чтобы быть более общим, оператор while должен учитывать также все другие теги, которые не могут содержать текст. Эти элементы называются элементы пустоту и этот вопрос есть несколько методов, как проверить, является ли элемент void. Итак, предполагая, что существует функция с именем canContainText возвращает true если аргумент не является элементом void, следующая строка кода:

contentEditableElement.lastChild.tagName.toLowerCase() != 'br'

заменить:

canContainText(getLastChildElement(contentEditableElement))

правка #2: приведенный выше код полностью обновляется, с каждым описанным и обсужденным изменением


решение 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);

можно установить курсор до конца через диапазон:

setCaretToEnd(target/*: HTMLDivElement*/) {
  const range = document.createRange();
  const sel = window.getSelection();
  range.selectNodeContents(target);
  range.collapse(false);
  sel.removeAllRanges();
  sel.addRange(range);
  target.focus();
  range.detach(); // optimization

  // set scroll to the end if multiline
  target.scrollTop = target.scrollHeight; 
}

У меня была аналогичная проблема, пытаясь сделать элемент редактируемым. Это было возможно в Chrome и FireFox, но в FireFox каретка либо шла в начало ввода, либо шла через одно пространство после окончания ввода. Очень запутанный для конечного пользователя, я думаю, пытаясь отредактировать контент.

Я не нашел решения, пытаясь несколько вещей. Единственное, что сработало для меня,-это "обойти проблему", поместив простой старый текстовый ввод внутри моего . Теперь это работает. Похоже "редактируемый контент" по-прежнему является технологией bleeding edge, которая может работать или не работать так, как вы хотели бы, в зависимости от контекста.