简单实现富文本编辑器
1、思路
在日常工作中,经常会使用到富文本编辑器,那么富文本到底是怎么实现的呢?
我也是第一次做富文本编辑器,一开始完全没有一点想法,脑子里唯一能想到的是用来做,但是查了资料,发现textarea支持多行文本输入,满足了我们编辑的很大需求。然而,textarea不能像div一样高度自适应,高度保持不变,内容大于高度时就会出现滚动条。而且textarea只支持文本输入,随着现在越来越关注用户体验,需求也越来越多,很多时候我们需要在编辑区域插入图片,链接,视频。
表示该区域为可编辑区域,可根据内容高度自适应,这样我们的富文本编辑区域就有了,但是我们还要对内容进行编辑,样式控制等,我们选择好了编辑内容以及样式,就需要一个命令去为我们执行这个命令,实现这些功能,document.execCommand(sCommand[,交互方式, 动态参数])这个命令就可以很好的解决这个问题,实现富文本的核心思想有了,我们就开始编写我们的第一个富文本编辑器把!
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="../js/jquery.min.js"></script>
<style type="text/css">
.editor_title {
line-height: 40px;
padding-left: 10px;
height: 40px;
width: 690px;
background-color: gainsboro;
}
.body {
margin-top: 30px;
margin-left: auto;
margin-right: auto;
height: 400px;
width: 700px;
border: 1px solid gainsboro;
}
.editor {
overflow: auto;
height: 360px;
width: 100%;
margin-left: 10px;
border: none;
outline: none;
}
select {
appearance: none;
-webkit-appearance: none;
-moz-appearance: none;
background-color: gainsboro;
outline: none;
border: none;
width: 40px;
height: 20px;
}
button {
background-color: gainsboro;
outline: none;
border: none;
width: 30px;
height: 20px;
}
</style>
</head>
<body>
<div class="body">
<!-- 该区域是功能区域,主要对编辑区域的内容进行样式控制 -->
<div class="editor_title">
<div>
<!-- 对内容进行文字大小的控制 -->
<select id="select_h" onchange="HExecute('#select_h','fontSize')" >
<option value="1">正文</option>
<option value="7">H1</option>
<option value="5">H2</option>
<option value="3">H3</option>
<option value="2">H4</option>
</select>
<!-- 对内容进行加粗 -->
<button onclick="execute('bold')" ><B>B</B></button>
<!-- 最内容进行颜色选择 -->
<select class="C-select" onchange="HExecute('.C-select','foreColor')">
<option value="">颜色</option>
<option value="black">黑</option>
<option value="red">红</option>
<option value="blue">蓝</option>
<option value="white">白</option>
</select>
</div>
</div>
<!-- 编辑区域 -->
<div class="editor" id="editor" contenteditable="true">
请输入编辑区的内容
</div>
</div>
</body>
<script type="text/javascript">
// 执行命令,有一定的格式,可参照相关命令
function execute(cmd,args=null){
document.execCommand(cmd,false,args)
}
function HExecute (id,cmd) {
let h = $(id).val();
execute(cmd,h)
}
</script>
</html>
效果图如下:
一个简单的富文本编辑器就做好了哟,有兴趣的可以继续完善该编辑器,希望我们文章对你们有所帮助!!
document.execCommand的一些常用命令还请自行百度。