簡體   English   中英

在標簽上的內容可編輯div中獲取focus()

[英]getting focus() inside a content editable div on tab

有一個主要的內容可編輯div,它顯示帶有占位符(下划線)的某些模板-在其中可能還有其他div,它們也是可編輯的。 里面的div有一個類-讓我們將其稱為突出顯示。

我希望能夠在其中跳至div並鍵入。

我給了內部divs一個tabIndex,這使它們可以顯示標簽,但除非明確單擊它們,否則無法鍵入。 我只想使用鍵盤就能做到這一點。

PS我需要一個JS解決方案,而不是jQuery的

用輸入/或文本區域替換內部div效果很好,除了,我想使用div或span

在另一個stackoverflow頁面上,我附加了一個事件偵聽器,檢查div是否具有我要查找的類,我在其上顯式調用了.blur()和.focus(),但這是行不通的

// partial code relevant to the problem

function contentEdit(text) {
    ....

    // replace placeholder text (underscores) with div
    // and maintain line breaks
    text = text.replace(/(\r\n|\n|\r)/gm, '<br/>')
        .replace(/[_]+/gm, '<div class="highlight" tabindex="0">  </div>');

    vm.content = '<div contenteditable>' + text + '</div>';

    var ce = document.getElementById('contenteditable-div');

    // tried this approach from stackoverflow
    ce.addEventListener('keydown', function(e) {
        if (e.keyCode == 9) {
            if (e.target.className == 'highlight') {
                e.target.blur();
                e.target.focus();
            }
        }
    });
    .......
}

模糊/焦點塊僅在條件為真時第二次觸發-因此,不是在第一次遇到該條件的div時觸發。

由於使用了tabIndex,瀏覽器似乎在進行分頁瀏覽時將焦點放在div上(上面有邊框突出顯示),但是除非單擊div,否則不會觸發輸入事件。 輸入或文本區域不是這種情況-出於某些原因,它們也成為焦點,但也接受關鍵輸入。

演示:codepen.io/anon/pen/bPEJjo

有什么想法/建議為何內部div無法接受鍵盤事件或如何觸發它們?

僅偵聽父級上的keyup(比keydown更好的計時),它將從子元素中冒泡。 然后為聚焦元素創建一個范圍,並將光標設置為其位置。 如下所示:

 function moveCursor(e) { if (e.key !== 'Tab') {return;} var element = document.activeElement, range = document.createRange(), selection = window.getSelection(); range.setStart(element, 0); range.collapse(true); selection.removeAllRanges(); selection.addRange(range); element.focus(); } document.getElementById('pad').addEventListener('keyup', moveCursor); 
 .ce { position: relative; width: 300px; height: 50px; border: 1px solid #000; margin-bottom: 1em; } 
 <div id="pad" contenteditable="true"> <div class="ce" tabindex="1"></div> <div class="ce" tabindex="2"></div> <div class="ce" tabindex="3"></div> <div class="ce" tabindex="4"></div> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM