2009-07-14 49 views
57

我需要將插入符號移動到contenteditable節點的末尾,就像在Gmail便箋小部件上一樣。如何將光標移動到可用實體的結尾

我在StackOverflow上讀取線程,但這些解決方案基於使用輸入,並且它們不適用於contenteditable元素。

回答

21

也有另一種問題。

如果contenteditable div不包含其他多線元素,則Nico Burns的解決方案有效。

例如,如果div包含其他div,並且這些其他div包含其他內容,則可能會發生一些問題。

爲了解決這些問題,我已經安排了以下解決方案,這是一個改善Nico的一個:

//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元素,並且在this question中有一些關於如何測試元素是否爲空的方法。因此,假設存在一個名爲canContainText函數,返回true如果參數不是一個空元素,下面的代碼行:

canContainText(getLastChildElement(contentEditableElement)) 

EDIT#2:

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

應替換:上面的代碼是完全更新的,每個變化描述和討論

183

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

你有辦法使這項工作在鉻? – Jason 2010-04-21 22:19:52

+1

geowa4的解決方案將用於chrome中的textarea,它不適用於任何瀏覽器中的contenteditable元素。我的工作是爲了滿足自己的要素,但不是爲textareas。 – 2010-10-05 18:11:14

+4

這是這個問題的正確答案,完美,謝謝尼科。 – Rob 2012-04-30 10:17:10

1

可以將光標設置到範圍末端:

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; 
} 
相關問題