簡體   English   中英

當用戶在該元素外單擊時,您如何避免失去對 contenteditable 元素的關注?

[英]How do you avoid losing focus on a contenteditable element when a user clicks outside that element?

如果在該區域外單擊,我想防止contentEditable區域失去焦點。 一些示例 HTML 如下所示:

<div id="content">
    <p>Hello</p>
</div>
<div id="clickThis">
    <p>If you click on this or anywhere for that matter after focusing on Hello, you lose your focus on Hello</p>
</div>

示例 Javascript 如下所示:

$(document).ready(function()
{
    $('#content')[0].contentEditable=true;

    $('#clickThis').bind('click',function(e)
    {
        console.log(window.getSelection().getRangeAt(0).startContainer);
        e.preventDefault();
    });
});

當您單擊#clickThis div 或#content div 之外的任何位置時,即使您調用 click 事件的preventDefault函數,您也會失去對#content div 的關注。

此外,范圍在點擊事件被觸發的那一刻發生變化,所以我不能在點擊發生后就回到上一個范圍。 有沒有辦法在點擊發生后保持光標位置和焦點?

jsFiddle: http : //jsfiddle.net/VivekVish/FKDhe/4/

把胡安的問題變成答案,而不是使用click事件,你必須使用mousedown事件,如下所示:

$(document).ready(function()
{
    $('#content')[0].contentEditable=true;

    $('#clickThis').bind('mousedown',function(e)
    {
        console.log(window.getSelection().getRangeAt(0).startContainer);
        e.preventDefault();
    });
});

你可以看到它在這里工作:

http://jsfiddle.net/FKDhe/7/

答案是將event.preventDefault()添加到mouseDown事件。

const button = document.getElementById('boldFormat')

button.addEventListener('mousedown', (event) => {
  event.preventDefault() // prevent loss of focus
  document.execCommand('bold', false)
})

出現問題是因為您正在偵聽導致contentEditable元素失去焦點的click事件; 無論您是否運行preventDefault

嘗試添加$('#content').focus(); e.preventDefault(); 這不是一個完美的解決方案,因為它跳到了開頭,但請嘗試一下。

無論如何,您確定強制用戶返回該區域是個好主意嗎? :)

暫無
暫無

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

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