为什么使用execCommand进行验证无法正常工作?检查以下代码:
$('#JustifyLeft').click(function(){
document.execCommand("JustifyLeft", false, "");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Select whole text and click the button</p>
<div class="editable" contenteditable="TRUE" style="font-size: 27px; text-align: center;">
<span style="font-weight: bold; font-style: italic; text-decoration: underline;">Hi<span style="font-size: 35px;">I</span>am<span style="font-size: 18px;">Blah Blah</span>Ok</span>
</div>
<input type="button" id="JustifyLeft" value="Align Left">
&#13;
选择整个文本并对其进行对齐后,您会看到下划线仅保留在<text>
个节点上,<span>
个节点没有文本修饰。
这是一个错误吗?有没有办法纠正它?
答案 0 :(得分:1)
如果您要查看开发人员工具中的元素结构,您会看到execCommand在 嗨,上午和之后 之后添加了结束</span>
并将其包装为<div>
如下所示
<div style="text-align: left;">
<span style="font-style: italic; font-weight: bold; text-decoration: underline;">Hi</span>
<span style="font-style: italic; font-weight: bold; font-size: 35px;">I</span>
<span style="font-style: italic; font-weight: bold; text-decoration: underline;">am</span>
<span style="font-style: italic; font-weight: bold; font-size: 18px;">Blah Blah</span>
<span style="font-style: italic; font-weight: bold; text-decoration: underline;">Ok</span>
</div>
您只需将第一个<span>
更改为<div>
,如下所示即可更正
<div style="font-weight: bold; font-style: italic; text-decoration: underline;">Hi
<span style="font-size: 35px;">I</span>am
<span style="font-size: 18px;">Blah Blah</span>Ok
</div>