簡體   English   中英

Contenteditable:如何在按del或退格時完全刪除跨度

[英]Contenteditable: How to completely remove span when pressing del or backspace

我有一個contenteditable div,如下面的HTML所示(插入標記為| )。

我想在按退格鍵刪除時刪除span.label (即span作為單個字母,因此對於用戶來說,看起來好像在一個單鍵中刪除了Name

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

您需要檢查光標是否位於跨度結束的確切位置,如果是,請將其刪除:

 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> 

我沒有實現del鍵功能,但總體思路就在那里,我認為你可以根據上面的例子來完成它

你可以在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);
                    });

                }

            }
        });

暫無
暫無

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

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