开发者

contentEditable, execCommand, and forcing newly typed text to be bolded

I'm fooling around with contentEditable and execCommand, and I'm trying to make it so that when a button is pressed,

  • If there's text selected in the contentEditable, it becomes bolded

  • If there's no text selected in the contentEditable, then any text typed in the contentEditable after pressing the button is bolded

I tried using the following Javascript command:

 document.execCommand('bold', false, null);

But unfortunately, that only caus开发者_开发百科es text that's selected to become bolded; if no text is selected and you start typing after pressing the button, the text shows up unbolded.

I noticed that if I press Ctrl+B in the contentEditable, it does exactly what I'd like to accomplish, but I'd like to accomplish this using Javascript (and without simulating a Ctrl+B in Javascript).


Actually the document.execCommand() call does exactly what you want (you can prove this by calling it from a keydown event handler), and I suspect it's the effect of whatever button or whatever else you may be using to trigger the command that's the problem.


Javascripts Range can check out selected text, see this link. You can use it to get the selected text (startnode, endnode, offset etc). If you want new text to be bold, just add it in a new created <p> that you give bold in css. BUT, this might not work in IE...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜