button 配合 document.execCommand() 实现文字加粗效果。
在实现富文本编辑器的点击按钮给文本文字加粗的时候遇到了一个问题,那就是当选中文字是点击加粗按钮会取消文字的选中。
想要的效果为:
想要实现此效果,只要将按钮换成 button 就可以了。
完整代码:
<style>
* {
padding: 0;
margin: 0;
}
html,
body {
padding: 20px;
background-color: #000000;
}
li {
list-style-type: none;
}
#editor {
width: 800px;
height: 360px;
border-radius: 6px;
background-color: #ffffff;
border: 1px solid #cccccc;
}
#editor .editor-toolbar {
display: flex;
flex-wrap: wrap;
padding: 8px;
border-bottom: 1px solid #cccccc;
}
#editor .editor-toolbar .editor-item {
width: 21px;
height: 21px;
line-height: 21px;
padding: 4px;
text-align: center;
cursor: pointer;
border: 0;
}
#editor .editor-toolbar .editor-item:hover {
background-color: #f1f1f1;
}
#editor .editor-toolbar .editor-item button {
border: 0;
outline: none;
background-color: unset;
cursor: pointer;
width: 100%;
height: 100%;
}
#editor .editor-text {
height: calc(100% - 62px);
padding: 8px;
overflow-y: auto;
}
#editor .editor-text ._wrapper {
width: 100%;
height: 100%;
box-sizing: border-box;
outline: 0;
}
</style>
<div id="editor">
<div class="editor-toolbar">
<div class="editor-item">
<button data-key="bold">B</button>
</div>
<div class="editor-item">
<button>U</button>
</div>
<div class="editor-item">
<button>I</button>
</div>
<div class="editor-item">
<button>=</button>
</div>
</div>
<div class="editor-text">
<div class="_wrapper" contenteditable="true"></div>
</div>
</div>
<script>
let editorItem = document.querySelectorAll("#editor .editor-toolbar .editor-item button");
editorItem.forEach(item => {
let key = item.dataset.key;
item.addEventListener("click", function (e) {
e.preventDefault();
e.stopPropagation();
console.log(window.getSelection().toString());
if (window.getSelection().toString().length > 0 && key === "bold") {
document.execCommand("bold", false, null);
}
});
});
</script>