javascript 当用户在该元素外单击时,您如何避免失去对 contenteditable 元素的关注?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7392959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:58:01  来源:igfitidea点击:

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

javascriptjavascript-eventscontenteditable

提问by Deets McGeets

I want to prevent a contentEditable area from losing focus if a click is made outside that area. Some sample HTML looks like this:

如果在该区域外单击,我想防止 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>

Sample javascript looks as follows:

示例 javascript 如下所示:

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

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

When you click on the #clickThisdiv or anywhere outside the #contentdiv, you lose focus on the #contentdiv even if you call the click event's preventDefault function.

当您点击#clickThisdiv 或 div 之外的任何地方时#content#content即使您调用 click 事件的 preventDefault 函数,您也会失去对div 的关注。

In addition, the range changes the moment the click event is fired, so I can't just return to the previous range after the click has occurred. Is there a way to maintain the cursor position and focus after a click occurs?

另外,范围在点击事件被触发的那一刻发生变化,所以我不能在点击发生后就回到上一个范围。有没有办法在点击发生后保持光标位置和焦点?

Thanks.

谢谢。

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

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

回答by Deets McGeets

Putting Juan's question into an answer, instead of using the click event, you have to use the mousedown event as follows:

把胡安的问题变成答案,而不是使用click事件,你必须使用mousedown事件,如下所示:

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

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

You can see it working here:

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

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

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

回答by szajmon

try adding $('#content').focus();after e.preventDefault();it's not a perfect solution, since it jumps to the beginning, but give it a try.

$('#content').focus();e.preventDefault();它不是一个完美的解决方案之后尝试添加,因为它会跳到开头,但请尝试一下。

anyway, are you sure it's a good idea to force the user back to this area? :)

无论如何,您确定强制用户返回该区域是个好主意吗?:)