contentEditable ExecCommand“粗体”无法触发

时间:2019-05-27 06:40:12

标签: javascript jquery html css contenteditable

我很难在我的contentEditable div上执行一个执行命令“ bold”。我在类似问题上尝试了很多解决方案,但均无济于事。我了解execCommand存在一些错误,非常感谢您的帮助! :)

这是我的HTML:

<div class="body">
        <button id="bolder" type="button">Bold</button>
        <div class="text"  contenteditable="true">
            I'm an asshole and wont work


        </div>
        <img class="loader" id="loader" src="Social_Icons/loader.svg">
    </div>

JS:

$("#bolder").on('click', function() {
      document.execCommand("bold", false, null);
    });

CSS:

.text {
position: relative;
width: 100%;
height: 90%;
left: 0%;
border: solid;

}

编辑:我正在使用最新的Chrome浏览器

1 个答案:

答案 0 :(得分:1)

您的代码运行正常。但是:

  • 如果只想使编辑器中的一些文本变为 strong ,则必须先选择文本。

  • 如果要使所有文本都变为 strong ,可以在应用document.execCommand('selectAll',false,null)之前使编辑器集中并使用bold选择所有文本。

此示例在单击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>

相关问题