我正在制作所见即所得的编辑器,但我没有使用execCommand()
函数,我遇到了粗体和斜体等问题。以下是我的代码。如果您尝试粗体仅加下划线或strikethroughed它将起作用,但如果您尝试使用两种样式(如下划线和删除线)粗体文本,则会出现错误。我该怎么修呢?
谢谢你的帮助。
$('#BoldButton').click(function ()
{
var elem = AddClassToSelected('bold');
//Chceck if inside created <span> isn't another <span> with bold class. If it is removed it.
$(elem).children().each(function (event) {
if ($(this).hasClass('bold')) {
$(this).replaceWith($(this).contents());
}
});
});
function AddClassToSelected(newClass){
var span = document.createElement("span");
span.className = newClass;
if (window.getSelection) {
var sel = window.getSelection();
if (sel.rangeCount) {
var range = sel.getRangeAt(0).cloneRange();
range.surroundContents(span);
sel.removeAllRanges();
sel.addRange(range);
}
}
return span;
}
&#13;
div {
width: 500px;
height: 300px;
border: 1px solid black;
}
.bold {
font-weight: bold;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="BoldButton">Bold</button>
<div contenteditable="true" spellcheck="false">
<u>SomeTextSomeText</u><strike>SomeTextSomeText</strike>
</div>
&#13;