問題描述

當一個 contentEditable = ‘on'< div> 時,我已經確定了一個 cross-browser 解決方案來設定遊標/插入符位置到最後一個已知位置。重新獲得關注。出現內容可編輯 div 的預設功能是每次單擊時將插入符號/遊標移動到 div 中文字的開頭,這是不希望的。

我相信當他們離開 div 的焦點時,我必須儲存一個變數當前的遊標位置,然後 re-set 這個當他們有焦點在裡面,但是我沒有能夠放在一起,或者找到一個工作的程式碼示例然而。

如果有人有任何想法,工作程式碼片段或樣本,我將很高興看到它們。

我真的沒有任何程式碼,但這裡是我做的:

<script type="text/javascript">
// jQuery
$(document).ready(function() {
   $('#area').focus(function() { .. }  // focus I would imagine I need.
}
</script>
<div id="area" contentEditable="true"></div>

PS 。我嘗試過這個資源,但它似乎不適用於< div> 。也許只有 textarea(How to move cursor to end of contenteditable entity)

最佳解決方案

這與 standards-based 瀏覽器相容,但 IE 可能會失敗。我提供它作為起點。 IE 不支援 DOM 範圍。

var editable = document.getElementById('editable'),
    selection, range;

// Populates selection and range variables
var captureSelection = function(e) {
    // Don't capture selection outside editable region
    var isOrContainsAnchor = false,
        isOrContainsFocus = false,
        sel = window.getSelection(),
        parentAnchor = sel.anchorNode,
        parentFocus = sel.focusNode;

    while(parentAnchor && parentAnchor != document.documentElement) {
        if(parentAnchor == editable) {
            isOrContainsAnchor = true;
        }
        parentAnchor = parentAnchor.parentNode;
    }

    while(parentFocus && parentFocus != document.documentElement) {
        if(parentFocus == editable) {
            isOrContainsFocus = true;
        }
        parentFocus = parentFocus.parentNode;
    }

    if(!isOrContainsAnchor || !isOrContainsFocus) {
        return;
    }

    selection = window.getSelection();

    // Get range (standards)
    if(selection.getRangeAt !== undefined) {
        range = selection.getRangeAt(0);

    // Get range (Safari 2)
    } else if(
        document.createRange &&
        selection.anchorNode &&
        selection.anchorOffset &&
        selection.focusNode &&
        selection.focusOffset
    ) {
        range = document.createRange();
        range.setStart(selection.anchorNode, selection.anchorOffset);
        range.setEnd(selection.focusNode, selection.focusOffset);
    } else {
        // Failure here, not handled by the rest of the script.
        // Probably IE or some older browser
    }
};

// Recalculate selection while typing
editable.onkeyup = captureSelection;

// Recalculate selection after clicking/drag-selecting
editable.onmousedown = function(e) {
    editable.className = editable.className + ' selecting';
};
document.onmouseup = function(e) {
    if(editable.className.match(/sselecting(s|$)/)) {
        editable.className = editable.className.replace(/ selecting(s|$)/, '');
        captureSelection();
    }
};

editable.onblur = function(e) {
    var cursorStart = document.createElement('span'),
        collapsed = !!range.collapsed;

    cursorStart.id = 'cursorStart';
    cursorStart.appendChild(document.createTextNode('—'));

    // Insert beginning cursor marker
    range.insertNode(cursorStart);

    // Insert end cursor marker if any text is selected
    if(!collapsed) {
        var cursorEnd = document.createElement('span');
        cursorEnd.id = 'cursorEnd';
        range.collapse();
        range.insertNode(cursorEnd);
    }
};

// Add callbacks to afterFocus to be called after cursor is replaced
// if you like, this would be useful for styling buttons and so on
var afterFocus = [];
editable.onfocus = function(e) {
    // Slight delay will avoid the initial selection
    // (at start or of contents depending on browser) being mistaken
    setTimeout(function() {
        var cursorStart = document.getElementById('cursorStart'),
            cursorEnd = document.getElementById('cursorEnd');

        // Don't do anything if user is creating a new selection
        if(editable.className.match(/sselecting(s|$)/)) {
            if(cursorStart) {
                cursorStart.parentNode.removeChild(cursorStart);
            }
            if(cursorEnd) {
                cursorEnd.parentNode.removeChild(cursorEnd);
            }
        } else if(cursorStart) {
            captureSelection();
            var range = document.createRange();

            if(cursorEnd) {
                range.setStartAfter(cursorStart);
                range.setEndBefore(cursorEnd);

                // Delete cursor markers
                cursorStart.parentNode.removeChild(cursorStart);
                cursorEnd.parentNode.removeChild(cursorEnd);

                // Select range
                selection.removeAllRanges();
                selection.addRange(range);
            } else {
                range.selectNode(cursorStart);

                // Select range
                selection.removeAllRanges();
                selection.addRange(range);

                // Delete cursor marker
                document.execCommand('delete', false, null);
            }
        }

        // Call callbacks here
        for(var i = 0; i < afterFocus.length; i++) {
            afterFocus[i]();
        }
        afterFocus = [];

        // Register selection again
        captureSelection();
    }, 10);
};

次佳解決方案

該解決方案適用於所有主流瀏覽器:

saveSelection()連線到 div 的 onmouseuponkeyup 事件,並將選擇儲存到變數 savedRange

restoreSelection()附加到 div 的 onfocus 事件,並重新選擇儲存在 savedRange 中的選擇。

這樣做完美,除非您希望在使用者單擊 div 時恢復選擇 (通常您希望遊標到達您點選的位置,但包含的程式碼完整性),這是非常不尋常的)

為了達到這個目的,onclickonmousedown 事件被 cancelEvent()功能取消,cancelEvent()是一種跨瀏覽器功能來取消事件。 cancelEvent()功能也執行 restoreSelection()功能,因為當單擊事件被取消時,div 不會接收到焦點,因此除非執行此功能,否則不會選擇任何內容。

變數 isInFocus 儲存是否對焦,並更改為”false” onblur 和”true” onfocus 。這樣,只有當 div 不在焦點時才能取消點選事件 (否則根本無法更改選擇) 。

如果您希望在 div 被焦點聚焦時進行選擇,而不是恢復選擇 onclick(並且只有當使用 document.getElementById("area").focus(); 或類似程式使用 document.getElementById("area").focus(); 或者類似程式才能將該元素重點放在元素上時,請簡單地刪除 onclickonmousedown 事件。 onblur 事件和 onDivBlur()cancelEvent()功能也可以在這些情況下安全地刪除。

如果要快速測試,該程式碼應該可以直接放入 html 頁面的正文中:

<div id="area" style="width:300px;height:300px;" onblur="onDivBlur();" onmousedown="return cancelEvent(event);" onclick="return cancelEvent(event);" contentEditable="true" onmouseup="saveSelection();" onkeyup="saveSelection();" onfocus="restoreSelection();"></div>
<script type="text/javascript">
var savedRange,isInFocus;
function saveSelection()
{
    if(window.getSelection)//non IE Browsers
    {
        savedRange = window.getSelection().getRangeAt(0);
    }
    else if(document.selection)//IE
    {
        savedRange = document.selection.createRange();
    }
}

function restoreSelection()
{
    isInFocus = true;
    document.getElementById("area").focus();
    if (savedRange != null) {
        if (window.getSelection)//non IE and there is already a selection
        {
            var s = window.getSelection();
            if (s.rangeCount > 0)
                s.removeAllRanges();
            s.addRange(savedRange);
        }
        else if (document.createRange)//non IE and no selection
        {
            window.getSelection().addRange(savedRange);
        }
        else if (document.selection)//IE
        {
            savedRange.select();
        }
    }
}
//this part onwards is only needed if you want to restore selection onclick
var isInFocus = false;
function onDivBlur()
{
    isInFocus = false;
}

function cancelEvent(e)
{
    if (isInFocus == false && savedRange != null) {
        if (e && e.preventDefault) {
            //alert("FF");
            e.stopPropagation(); // DOM style (return false doesn't always work in FF)
            e.preventDefault();
        }
        else {
            window.event.cancelBubble = true;//IE stopPropagation
        }
        restoreSelection();
        return false; // false = IE style
    }
}
</script>

第三種解決方案

更新

我編寫了一個 cross-browser 系列和選擇庫,名為 Rangy,其中包含了我在下面釋出的程式碼的改進版本。您可以將 selection save and restore module 用於此特定問題,儘管如果您在專案中沒有選擇任何其他選項,並且不需要大量的庫,我也會嘗試使用像 @Nico Burns’s answer 這樣的東西。

以前的答案

您可以使用 IERange(http://code.google.com/p/ierange/) 將 IE 的 TextRange 轉換為 DOM 範圍,並將其與眼瞼的起點結合使用。就我個人而言,我將只使用來自 IERange 的演演算法進行 Range< – > TextRange 轉換而不是使用整個事情。而 IE 的選擇物件沒有 focusNode 和 anchorNode 屬性,但是您應該只能使用從選擇中獲取的 Range /TextRange 。

我可以把東西放在一起去做,如果我做的話會發貼到這裡。

編輯:

我已經建立了一個指令碼的演示,這樣做。除了 Opera 9 中的一個 bug,我還沒有時間研究之外,它在我嘗試過的所有內容中起作用。它的工作原理是 IE 5.5,6 和 7,Chrome 2,Firefox 2,3 和 3.5 以及 Safari 4,都在 Windows 上。

http://www.timdown.co.uk/code/selections/

請注意,可以在瀏覽器中進行選擇,以使焦點節點處於選擇開始,並且擊中右遊標鍵或左遊標鍵將將插入符號移動到相對於選擇開始的位置。我不認為在還原選擇時可以複製它,所以焦點節點始終處於選擇結束。

我會在稍後寫完這個。

第四種方案

我有一個相關的情況,我特別需要將遊標位置設定為可內容 div 的 END 。我不想使用像 Rangy 這樣一個完整的 Library ,許多解決方案太重了。

最後,我想出了這個簡單的 jQuery 函式,將克拉位置設定為可內容的 div 結尾:

$.fn.focusEnd = function() {
    $(this).focus();
    var tmp = $('<span />').appendTo($(this)),
        node = tmp.get(0),
        range = null,
        sel = null;

    if (document.selection) {
        range = document.body.createTextRange();
        range.moveToElementText(node);
        range.select();
    } else if (window.getSelection) {
        range = document.createRange();
        range.selectNode(node);
        sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    }
    tmp.remove();
    return this;
}

理論很簡單:將一個 span 附加到可編輯的末尾,選擇它,然後刪除 span – 在 div 的末尾留下一個遊標。您可以調整此解決方案以將任何位置插入到任何位置,從而將遊標放在特定位置。

用法很簡單:

$('#editable').focusEnd();

而已!

第五種方案

我拿了 Nico Burns 的答案,並使用了 jQuery:

  • 通用型:適用於每個 div contentEditable="true"

你需要 jQuery 1.6 或更高版本:

savedRanges = new Object();
$('div[contenteditable="true"]').focus(function(){
    var s = window.getSelection();
    var t = $('div[contenteditable="true"]').index(this);
    if (typeof(savedRanges[t]) === "undefined"){
        savedRanges[t]= new Range();
    } else if(s.rangeCount > 0) {
        s.removeAllRanges();
        s.addRange(savedRanges[t]);
    }
}).bind("mouseup keyup",function(){
    var t = $('div[contenteditable="true"]').index(this);
    savedRanges[t] = window.getSelection().getRangeAt(0);
}).on("mousedown click",function(e){
    if(!$(this).is(":focus")){
        e.stopPropagation();
        e.preventDefault();
        $(this).focus();
    }
});



savedRanges = new Object();
$('div[contenteditable="true"]').focus(function(){
    var s = window.getSelection();
    var t = $('div[contenteditable="true"]').index(this);
    if (typeof(savedRanges[t]) === "undefined"){
        savedRanges[t]= new Range();
    } else if(s.rangeCount > 0) {
        s.removeAllRanges();
        s.addRange(savedRanges[t]);
    }
}).bind("mouseup keyup",function(){
    var t = $('div[contenteditable="true"]').index(this);
    savedRanges[t] = window.getSelection().getRangeAt(0);
}).on("mousedown click",function(e){
    if(!$(this).is(":focus")){
        e.stopPropagation();
        e.preventDefault();
        $(this).focus();
    }
});
div[contenteditable] {
    padding: 1em;
    font-family: Arial;
    outline: 1px solid rgba(0,0,0,0.5);
}
<script src="https://googleajax.admincdn.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contentEditable="true"></div>
<div contentEditable="true"></div>
<div contentEditable="true"></div>

第六種方案

玩過之後,我修改了上面的 eyelidlessness 的答案,並將其作為一個 jQuery 外掛,所以你可以做以下之一:

var html = "The quick brown fox";
$div.html(html);

// Select at the text "quick":
$div.setContentEditableSelection(4, 5);

// Select at the beginning of the contenteditable div:
$div.setContentEditableSelection(0);

// Select at the end of the contenteditable div:
$div.setContentEditableSelection(html.length);

請問長程式碼帖子,但可能會幫助某人:

$.fn.setContentEditableSelection = function(position, length) {
    if (typeof(length) == "undefined") {
        length = 0;
    }

    return this.each(function() {
        var $this = $(this);
        var editable = this;
        var selection;
        var range;

        var html = $this.html();
        html = html.substring(0, position) +
            '<a id="cursorStart"></a>' +
            html.substring(position, position + length) +
            '<a id="cursorEnd"></a>' +
            html.substring(position + length, html.length);
        console.log(html);
        $this.html(html);

        // Populates selection and range variables
        var captureSelection = function(e) {
            // Don't capture selection outside editable region
            var isOrContainsAnchor = false,
                isOrContainsFocus = false,
                sel = window.getSelection(),
                parentAnchor = sel.anchorNode,
                parentFocus = sel.focusNode;

            while (parentAnchor && parentAnchor != document.documentElement) {
                if (parentAnchor == editable) {
                    isOrContainsAnchor = true;
                }
                parentAnchor = parentAnchor.parentNode;
            }

            while (parentFocus && parentFocus != document.documentElement) {
                if (parentFocus == editable) {
                    isOrContainsFocus = true;
                }
                parentFocus = parentFocus.parentNode;
            }

            if (!isOrContainsAnchor || !isOrContainsFocus) {
                return;
            }

            selection = window.getSelection();

            // Get range (standards)
            if (selection.getRangeAt !== undefined) {
                range = selection.getRangeAt(0);

                // Get range (Safari 2)
            } else if (
                document.createRange &&
                selection.anchorNode &&
                selection.anchorOffset &&
                selection.focusNode &&
                selection.focusOffset
            ) {
                range = document.createRange();
                range.setStart(selection.anchorNode, selection.anchorOffset);
                range.setEnd(selection.focusNode, selection.focusOffset);
            } else {
                // Failure here, not handled by the rest of the script.
                // Probably IE or some older browser
            }
        };

        // Slight delay will avoid the initial selection
        // (at start or of contents depending on browser) being mistaken
        setTimeout(function() {
            var cursorStart = document.getElementById('cursorStart');
            var cursorEnd = document.getElementById('cursorEnd');

            // Don't do anything if user is creating a new selection
            if (editable.className.match(/sselecting(s|$)/)) {
                if (cursorStart) {
                    cursorStart.parentNode.removeChild(cursorStart);
                }
                if (cursorEnd) {
                    cursorEnd.parentNode.removeChild(cursorEnd);
                }
            } else if (cursorStart) {
                captureSelection();
                range = document.createRange();

                if (cursorEnd) {
                    range.setStartAfter(cursorStart);
                    range.setEndBefore(cursorEnd);

                    // Delete cursor markers
                    cursorStart.parentNode.removeChild(cursorStart);
                    cursorEnd.parentNode.removeChild(cursorEnd);

                    // Select range
                    selection.removeAllRanges();
                    selection.addRange(range);
                } else {
                    range.selectNode(cursorStart);

                    // Select range
                    selection.removeAllRanges();
                    selection.addRange(range);

                    // Delete cursor marker
                    document.execCommand('delete', false, null);
                }
            }

            // Register selection again
            captureSelection();
        }, 10);
    });
};

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇