1. ホーム
  2. javascript

[解決済み] contenteditableエンティティの末尾にカーソルを移動させる方法

2022-11-17 22:10:39

質問

の末尾にキャレットを移動させたい。 contenteditable ノードの末尾に移動させる必要があります。

StackOverflowのスレッドを読みましたが、それらの解決策は入力を使用することに基づいており、それらは contenteditable 要素では動作しません。

どのように解決するのですか?

また、別の問題もあります。

ニコ・バーンズ の解決策は、もし contenteditable div が他の複数行の要素を含んでいない場合に動作します。

例えば、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要素 と名付けられ この質問 には、要素がvoidであるかどうかをテストする方法がいくつかあります。という関数が存在すると仮定すると canContainText という関数があり、それが true 引数が void 要素でない場合は、次のようなコード行になります。

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

に置き換える必要があります。

canContainText(getLastChildElement(contentEditableElement))

EDIT #2 : 上記のコードは完全に更新され、すべての変更が説明され、議論されています。