7

私はこのマークアップを持っています

<div contentEditable="true">
    Some other editable content
    <div class="field" contentEditable="false">
        <span class="label">This is the label</span>
        <span class="value" contentEditable="true">This is where the caret is</span>
    </div>
    <!-- This is where I want the Caret -->
</div>

カレットは現在.fieldスパンにあります。

親のに戻す必要があります。.fieldcontentEditable

例

これは、javascriptを介して(必要に応じてjQueryを使用して)どのように実現できますか?

図のように、キャレットが.valueスパンにある場合、キーダウンイベントでトリガーしようとします。

4

2 に答える 2

3

この次のセクションに進みたいと思います。わかりやすくするために、「Here!」というテキストを追加しました。デモでそれが最後まで行くことをあなたに示すために。

以下のデモでは、Enter keyから.field .valueを押して最後に移動します。

デモ:http: //jsfiddle.net/GLzKy/1/

以下は、実際にすべての作業を行うhttps://stackoverflow.com/a/4238971/297641の関数です。

$('.field .value').keydown(function (e) {
    if (e.which == 13) { //Enter Key
        e.preventDefault();            
        placeCaretAtEnd($(this).closest('.parent')[0]);
    }
});

/**
  This below function is from https://stackoverflow.com/a/4238971/297641
  All credits goes to the original author.
*/
function placeCaretAtEnd(el) {
    el.focus();
    if (typeof window.getSelection != "undefined"
            && typeof document.createRange != "undefined") {
        var range = document.createRange();
        range.selectNodeContents(el);
        range.collapse(false);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (typeof document.body.createTextRange != "undefined") {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.collapse(false);
        textRange.select();
    }
}

FF、IE8、Chromeでテスト済み

参照: https ://stackoverflow.com/a/4238971/297641

于 2013-01-24T23:21:22.970 に答える
3

An update to the previous answer. http://jsfiddle.net/GLzKy/4/

placeCaretAtEnd($(this).parent().nextAll('.field').children('value'));

UPDATE

Updated answer with correct answer in comments

For moving directly after the current field, you might want to use range.setStartAfter and range.setEndAfter: http://jsfiddle.net/GLzKy/5

于 2013-01-25T23:54:16.793 に答える