效果
源码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
:focus {
outline: none;
}
.container {
width: 500px;
height: 500px;
border: 1px solid black;
overflow: auto;
}
</style>
</head>
<body>
<div class="container" contentEditable="true">
舜发于畎亩之中,傅说举于版筑之间,胶鬲举于鱼盐之中,管夷吾举于士,孙叔敖举于海,百里奚举于市。故天将降大任于是人也,必先苦其心志,劳其筋骨,饿其体肤,空乏其身,行拂乱其所为,所以动心忍性,曾益其所不能。 人恒过,然后能改,困于心衡于虑而后作,征于色发于声而后喻。入则无法家拂士,出则无敌国外患者,国恒亡,然后知生于忧患而死于安乐也。
</div>
<button "document.execCommand('fontSize',false,7)">
h1
</button>
<button "document.execCommand('fontSize',false,5)">
h2
</button>
<button "document.execCommand('fontSize',false,3)">
h3
</button>
<button "document.execCommand('fontSize',false,2)">
h4
</button>
<button "document.execCommand('fontSize',false,1)">
h5
</button>
<button "document.execCommand('underline',false,null)">
u
</button>
<button "document.execCommand('bold',false,null)">
B
</button>
<button "document.execCommand('undo',false,null)">
撤销
</button>
<button "document.execCommand('redo',false,null)">
重做
</button>
<button "insertImg()"> 图片
</button>
<input type='color' "document.execCommand('forecolor',false,this.value)">
<script>
function insertImg() {
let value = prompt('请输入图片宽高', '100,100');
if (value && value != null) {
let tempArr = value.split(',')
let src = 'http://www.people.com.cn/h/pic/20140918/69/4985902989970457161.jpg'
document.execCommand('inserthtml', false, `<img src=${src} style='width:${tempArr[0]}px;height:${tempArr[1]}px'>`)
}
}
</script>
</body>
</html>
说明
代码中的onclick被csdn自动去掉了,要想运行案例,需要自己加上