contentEditable、execCommand 以及强制新键入的文本加粗
我正在玩弄 contentEditable 和 execCommand,并且我试图做到这一点,以便当按下按钮时,
如果在 contentEditable 中选择了文本,它将变为粗体
如果在 contentEditable 中没有选择文本,则按下按钮后在 contentEditable 中键入的任何文本都会加粗
我尝试使用以下Javascript命令:
document.execCommand('bold', false, null);
但不幸的是,这只会导致所选文本变为粗体;如果未选择任何文本并且您在按下按钮后开始输入,则文本将以非粗体显示。
我注意到,如果我在 contentEditable 中按 Ctrl+B,它正是我想要完成的任务,但我想使用 Javascript 来完成此任务(并且无需在 Javascript 中模拟 Ctrl+B)。
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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上
document.execCommand()
调用正是您想要的(您可以通过从keydown
事件处理程序调用它来证明这一点),我怀疑这是任何效果按钮或任何其他您可能用来触发问题的命令。Actually the
document.execCommand()
call does exactly what you want (you can prove this by calling it from akeydown
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 可以查看选定的文本,请参阅此链接。您可以使用它来获取选定的文本(起始节点、结束节点、偏移量等)。如果您希望新文本变为粗体,只需将其添加到您在 css 中提供粗体的新创建的
中即可。但是,这在 IE 中可能不起作用......
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...