<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>富文本编辑器</title>
</head>
<body>
<div contenteditable="true" id="editor"></div>
<button onclick="bold()">加粗</button>
<button onclick="italic()">斜体</button>
<button onclick="underline()">下划线</button>
<button onclick="fontSize()">字号</button>
<button onclick="fontColor()">字体颜色</button>
<button onclick="getHtml()">获取 HTML</button>
<script>
var editor = document.getElementById("editor");
function bold() {
document.execCommand("bold", false, null);
}
function italic() {
document.execCommand("italic", false, null);
}
function underline() {
document.execCommand("underline", false, null);
}
function fontSize() {
var size = prompt("请输入字号", "16px");
document.execCommand("fontSize", false, size);
}
function fontColor() {
var color = prompt("请输入颜色", "#000000");
document.execCommand("foreColor", false, color);
}
function getHtml() {
var html = editor.innerHTML;
console.log(html);
}
</script>
</body>
</html>
使用了一个带有 contenteditable
属性的 div
元素作为编辑区域。当用户点击按钮时,对应的 JavaScript 函数会调用 document.execCommand()
方法,从而改变当前选中的文本的样式或属性。具体而言,我们使用以下四个方法:
bold()
:将当前选中文本的字体加粗;italic()
:将当前选中文本的字体设置为斜体;underline()
:将当前选中文本的字体添加下划线;fontSize()
:弹出一个提示框,让用户输入字号,然后将当前选中文本的字体大小设置为用户输入的值;fontColor()
:弹出一个提示框,让用户输入颜色,然后将当前选中文本的字体颜色设置为用户输入的值。
当用户点击按钮时,对应的函数会被调用,然后执行 document.execCommand()
方法,它会将当前选中文本的样式或属性修改为函数指定的值。需要注意的是,由于 execCommand()
方法在一些浏览器中已经被废弃,我们需要考虑使用其他替代方案。