Dee*_*ets 9 javascript javascript-events contenteditable
如果在该区域外单击,我想阻止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>
Run Code Online (Sandbox Code Playgroud)
示例javascript如下所示:
$(document).ready(function()
{
$('#content')[0].contentEditable=true;
$('#clickThis').bind('click',function(e)
{
console.log(window.getSelection().getRangeAt(0).startContainer);
e.preventDefault();
});
});
Run Code Online (Sandbox Code Playgroud)
当你点击#clickThisdiv或div之外的任何地方时#content,#content即使你调用click事件的preventDefault函数,你也会失去对div的关注.
此外,范围会在click事件触发的那一刻发生变化,所以我不能在点击发生后返回上一个范围.有没有办法在点击发生后保持光标位置和焦点?
谢谢.
jsFiddle:http://jsfiddle.net/VivekVish/FKDhe/4/
Dee*_*ets 35
将Juan的问题放到答案中,而不是使用click事件,您必须使用mousedown事件,如下所示:
$(document).ready(function()
{
$('#content')[0].contentEditable=true;
$('#clickThis').bind('mousedown',function(e)
{
console.log(window.getSelection().getRangeAt(0).startContainer);
e.preventDefault();
});
});
Run Code Online (Sandbox Code Playgroud)
你可以看到它在这里工作: