【问题标题】:contentEditable ExecCommand "bold" fails to firecontentEditable ExecCommand“粗体”无法触发
【发布时间】:2019-05-27 06:40:11
【问题描述】:

在我的contentEditable div 上执行“粗体”命令时遇到了很多麻烦。我在这里尝试了很多类似问题的解决方案,但无济于事。我了解 execCommand 存在一些错误;任何帮助将不胜感激!

这是我的代码:

$("#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>

我使用的是最新的 Chrome 浏览器。

【问题讨论】:

    标签: javascript jquery html css contenteditable


    【解决方案1】:

    您的代码运行良好。但是:

    • 如果你只是想让编辑器内的一些文本变成strong,你必须先选择文本。

    • 如果你想让所有的文字都变成strong,你可以聚焦编辑器,在应用bold之前使用document.execCommand('selectAll',false,null)选择所有的文字。

    这个例子使点击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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多