Вопрос

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 causes 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...

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top