简体   繁体   English

contentEditable ExecCommand“粗体”无法触发

[英]contentEditable ExecCommand "bold" fails to fire

I'm having a lot of trouble getting an execcommand "bold" to fire on my contentEditable div.在我的contentEditable div 上使用“粗体”执行命令时遇到了很多麻烦。 I've tried a lot of solutions on similar questions here to no avail.我在这里尝试了很多类似问题的解决方案,但无济于事。 I understand there are some bugs with execCommand;我知道 execCommand 有一些错误; any help would be very much appreciated!任何帮助将不胜感激!

This is my code:这是我的代码:

 $("#bolder").on('click', function() { document.execCommand("bold", false, null); });
 .text { position: relative; width: 100%; height: 90%; left: 0%; border: solid; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="body"> <button id="bolder" type="button">Bold</button> <div class="text" contenteditable="true"> This won't work </div> <img class="loader" id="loader" src="Social_Icons/loader.svg"> </div>

I'm using the latest Chrome browser.我正在使用最新的 Chrome 浏览器。

Your code is working fine.您的代码运行良好。 But:但:

  • If you just want to make some text inside the editor becomes strong , you have to select the text first.如果只是想让编辑器里面的一些文字,就得先选中文字。

  • If you want to make all of the text becomes strong , you can focus the editor and use document.execCommand('selectAll',false,null) to select all of the text before applying bold .如果你想让所有的文本变得浓烈,你可以聚焦编辑器并使用document.execCommand('selectAll',false,null)在应用bold之前选择所有文本。

This example to make all of the text to bold after clicking Bold button:此示例在单击Bold按钮后使所有文本变为粗体

 $("#bolder").on('click', function() { $('[contenteditable]').focus(); document.execCommand('selectAll',false,null) document.execCommand("bold", false, null); });
 .text { position: relative; width: 100%; height: 90%; left: 0%; border: solid; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="body"> <button id="bolder" type="button">Bold</button> <div class="text" contenteditable="true"> This won't work </div> <img class="loader" id="loader" src="Social_Icons/loader.svg"> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM