HTML5---contentEditable属性 document.execCommand()函数设置文本粗斜体等

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<div id="btnGroup">
		<button id="bold"><bold>加粗</bold></button>
		<button id="i"><i>斜体</i></button>
		<button id="underline"><u>下划线</u></button>
		<button id="bgcolor" style="background-color: red">背景色</button>
	</div>
	
	<p contenteditable="true">我是本来的文字</p>
</body>
</html>

<script src="jquery.min.js"></script>
<script>
// 模拟编辑器 设置文字的背景色 字体等
// 需求助于document.execCommand函数.
// document.execCommand("backcolor","false","red"); 
// 三个参数为:要执行的命令、是否为当前命令提供用户界面、命令相关的值




//这里用了面向对象  可作练习
function Editor(selector){
	//jquery对象前加$符号是个好习惯
	this.$editor = $(selector);
	//私有函数为它加上下划线_  是在Javascript编程中普遍被遵守的约定
	this.bindEvents_();
}
Editor.prototype.bindEvents_ = function(){
	//真实的编辑器可能有十多个按钮,使用事件代理可提高效率
	this.$editor.on('click', 'button', function(event) {
		var id = event.currentTarget.id;
		switch(id){
			case "bold" :
			//大多数情况下后面两个参数可省略
				document.execCommand('bold');
				break;
			case "i" :
				document.execCommand('italic');
				break;
			case "underline" :
				document.execCommand('underline');
				break;
			case "bgcolor" :
				document.execCommand('backcolor','false','red');
				break;
		}
	});
}
new Editor('#btnGroup'); //初始化编辑器

</script>

猜你喜欢

转载自blog.csdn.net/qq_39201210/article/details/80665752