2017-08-10 1 views
6

以下のHTML(|でマークされている)に示すように、contenteditable divがあります。Contenteditable:delまたはbackspaceを押したときにスパンを完全に削除する方法

<div contenteditable="true"> 
    Hallo, <span class="label">Name</span>|, 
    this is a demonstration of placeholders! 
    Sincerly, your 
    <span class="label">Author</span> 
</div> 
Nameは、1回のキー操作で削除されたかのように見えるのユーザーにこのように、単一の文字としてすなわちスパン行為) バックスペースまたは を削除を押したとき

私はspan.labelを削除したいですあなたができる

答えて

7

あなたはカーソルがスパンの終わりの正確な位置にあるかどうかを確認する必要があり、もしそうなら - それを削除します。

document.querySelector('div').addEventListener('keydown', function(event) { 
 
    // Check for a backspace 
 
    if (event.which == 8) { 
 
     s = window.getSelection(); 
 
     r = s.getRangeAt(0) 
 
     el = r.startContainer.parentElement 
 
     // Check if the current element is the .label 
 
     if (el.classList.contains('label')) { 
 
      // Check if we are exactly at the end of the .label element 
 
      if (r.startOffset == r.endOffset && r.endOffset == el.textContent.length) { 
 
       // prevent the default delete behavior 
 
       event.preventDefault(); 
 
       if (el.classList.contains('highlight')) { 
 
        // remove the element 
 
        el.remove(); 
 
       } else { 
 
        el.classList.add('highlight'); 
 
       } 
 
       return; 
 
      } 
 
     } 
 
    } 
 
    event.target.querySelectorAll('span.label.highlight').forEach(function(el) { el.classList.remove('highlight');}) 
 
});
span.label.highlight { 
 
    background: #E1ECF4; 
 
    border: 1px dotted #39739d; 
 
}
<div contenteditable="true"> 
 
Hallo, <span class="label">Name</span>|, 
 
this is a demonstration of placeholders! 
 
</div>

私はdidnのをdelのキー機能を実装していませんが、一般的な考え方があり、上記の例に基づいて完成させることができます。

+0

うわー、これははじめてです、私はjavascriptの範囲/選択問題に役立つ答えを得ることができます。よくやった! – Tobi

+0

私は実際に範囲/選択に関する過去のいくつかの質問に答えました:)私は助けてくれると嬉しいです。 – Dekel

+0

@Delel、範囲や選択項目に関する良い読解をお勧めしますか?今私たちのアプリケーションにLabelと '@ mention'システムを実装しているので、私はいくつかの問題を抱えています。 – Tobi

1

は、divの上にonKeyDownイベントに耳を傾け:イベントはここで

<div contenteditable="true" id="editable"> 
Hallo, <span class="label">Name</span>|, 
this is a demonstration of placeholders! 
</div> 

を聞いているハンドラ:

 document.addEventListener('keydown', function (e) { 
      var keycode = event.keyCode; 
      console.log(keycode); 
      if (keycode === 8 || keycode === 46) { 
       var spnLables = document.querySelectorAll('#editable span.label'); 
       if (spnLables.length) { 
        Array.prototype.forEach.call(spnLables, function (thisnode) { 
         document.getElementById('editable').removeChild(thisnode); 
        }); 

       } 

      } 
     }); 
+0

私の言うことを明確にするために私の質問が更新されました。 – Tobi

+1

は、編集した回答に従ってコードを編集しました。 – asmmahmud

関連する問題