4 ответов:
есть и другая проблема.
The Нико Горитрешение работает, если
contenteditablediv не содержит других многолинейных элементов.например, если div содержит другие дивы, и эти другие дивы содержат другие вещи внутри, могут возникнуть некоторые проблемы.
для того, чтобы решить их, я организовал следующее решение, то есть улучшение Нико ' s один:
//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);таким образом, курсор обязательно располагается в конце последнего элемента, в конечном итоге вложенного.
EDIT #1: чтобы быть более общим, оператор while должен учитывать также все другие теги, которые не могут содержать текст. Эти элементы называются элементы пустоту и этот вопрос есть несколько методов, как проверить, если элемент является пустым. Итак, предполагая, что существует функция с именем
canContainTextвозвращаетtrueесли аргумент не является элементом void, то следующая строка кода:contentEditableElement.lastChild.tagName.toLowerCase() != 'br'заменить:
canContainText(getLastChildElement(contentEditableElement))EDIT #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 каретка либо шла к началу ввода, либо шла через один пробел после окончания ввода. Очень запутанно для конечного пользователя, я думаю, пытаясь отредактировать контент.
Я не нашел решения, пытаясь несколько вещей. Единственное, что сработало для меня,-это "обойти проблему", поместив простой старый текстовый ввод внутри моего . Теперь это работает. Похоже "контент-редактируемый" по-прежнему кровоточит edge tech, который может работать или не работать так, как вы хотели бы, в зависимости от контекста.
Comments