利用document.execCommand實現簡單的文本編輯功能,代碼如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>contenteditable</title>
</head>
<body>
<button οnclick="deleteSty()">刪除</button>
<button οnclick="insertHorizontalRuleSty()">插入水平線</button>
<div contenteditable style="border:1px solid; width:600px; min-height: 300px">
<img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1564893892182&di=a13fd00a7e9b6a419bc5eaeed36c93c1&imgtype=0&src=http%3A%2F%2F06.imgmini.eastday.com%2Fmobile%2F20171130%2F20171130032840_40b6bd9db5b3e14d0eb89d42235f1df3_4.jpeg" />
</div>
<script>
var deleteSty = function(){
document.execCommand('delete') //刪除選中的部分
}
var insertHorizontalRuleSty = function(){
document.execCommand('insertHorizontalRule') //在插入點插入一個水平線(刪除選中的部分)
}
</script>
</body>
</html>
選擇文字點擊刪除可以刪除掉對應的文字,想要具體實現文本的其他的編輯功能,請參考文檔document.execCommand Api文檔鏈接的其他api