execCommand后返回焦点到contenteditable?

我有以下代码演示contenteditable属性和一个按钮,将粗体文本注入带有contenteditable区域的段落。 我的问题是如何将焦点返回到我在单击粗体后停​​止的位置,如果突出显示某些文本,然后单击粗体,则会将这些文本加粗,但焦点将不再存在。 如果您没有选择任何内容并单击粗体,焦点将消失,如果您再次单击中断的位置,则可以输入粗体文本。

非常感谢您的帮助!

  #container{ width:500; } .handle{ float:left; }     $(function(){ $('#bold').click(function (){ document.execCommand('bold', false, true); }); });    

Some text here asdf asdf asdf asdf asdf asd fasd fsa dfsa df asdf sadf sa dfa sdf sadf asd fsa df sadf asdf asdf asd fas df asdf as

Some text here asdf asdf asdf asdf asdf asd fasd fsa dfsa df asdf sadf sa dfa sdf sadf asd fsa df sadf asdf asdf asd fas df asdf as

你应该使用.contents()

 var current; $(function(){ $("p[contenteditable]").focus(function() { current = this; }); $('#bold').click(function (){ document.execCommand('bold', false, true); $(current).contents().focus(); }); }); 

你可以使用jQuery .focus()函数来聚焦它。 这应该工作:

 var current; $(function(){ $("p[contenteditable]").focus(function() { current = this; }); $('#bold').click(function (){ document.execCommand('bold', false, true); $(current).focus(); }); }); 

这只是在每次用户聚焦时跟踪当前编辑的字段,并且当点击粗体按钮时,焦点被设置回该字段。

HTML:

  

JavaScript的:

 function doRichEditCommand(aName, aArg){ getIFrameDocument('editorWindow').execCommand(aName,false, aArg); document.getElementById('editorWindow').contentWindow.focus() } 

请参考这可以帮助您:

https://developer.mozilla.org/en/Rich-Text_Editing_in_Mozilla

您可能希望将最后单击的项存储在变量中,然后在执行.execCommand后在其上调用.focus() 。 我想这样的事情:

  $(function(){ $('p.editable').click(function() { var clickedItem = $(this); clickedItem.attr('contenteditable', true).focus(); $('#bold').click(function (){ document.execCommand('bold', false, true); clickedItem.focus(); }); }); }); 

这样你也可以从标记中删除"contenteditable"属性……

HTH

如果您在iframe中,请在默认视图上调用focus()。

 myiframedocument.execCommand('Bold',false,null); myiframedocument.defaultView.focus();