execCommand
當一個 HTML 文檔切換到設計模式(designMode)時,文檔對象暴露 execCommand 方法,該方法允許運行命令來操縱可編輯區域的內容。大多數命令影響文檔的選擇(粗體,斜體等),而其他命令插入新元素(添加鏈接)或影響整行(縮進)。當使用 contentEditable 時,調用 execCommand() 將影響當前活動的可編輯元素。
1.用法:
bool = document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)
1. 返回值
一個 Boolean類型 ,如果是 false 則表示操作不被支持或未被啟用。
2. 參數
2.1 aCommandName
一個 DOMString ,命令的名稱。可用命令列表請參閱 命令 。
2.2 aShowDefaultUI
一個 Boolean 是否展示用戶界面,一般為 false。Mozilla 沒有實現。
2.3 aValueArgument
一些命令需要一些額外的參數值(如insertimage需要提供這個image的url)。默認為null。
3. 命令(只選取一些下面代碼有用到的命令)
3.1 bold
開啟或關閉選中文字或插入點的粗體字效果。IE 瀏覽器使用 <strong> 標簽,而不是 <b> 標簽。
3.2 copy
拷貝當前選中內容到剪貼板。啟用這個功能的條件因瀏覽器不同而不同,而且不同時期,其啟用條件也不盡相同。使用之前請檢查瀏覽器兼容表,以確定是否可用。
3.3 fontSize
在插入點或者選中文字部分修改字體大小. 需要提供一個HTML字體尺寸 (1-7) 作為參數。
3.4 hiliteColor
更改選擇或插入點的背景顏色。需要一個顏色值字符串作為值參數傳遞。 UseCSS 必須開啟此功能。(IE瀏覽器不支持)
3.5 italic
在光標插入點開啟或關閉斜體字。 (Internet Explorer 使用 EM 標簽,而不是 I )
3.6 underline
在光標插入點開啟或關閉下划線。
4. 簡單富文本例子

(沒加樣式比較粗糙)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<iframe id='HtmlEdit' style="width:400px; height: 300px" marginWidth='2px' marginHeight='2px'></iframe>
<div id="butGroup">
<button id="bold">加粗</button>
<button id="copy">復制</button>
<button id="big">變大</button>
<button id="italic">斜體</button>
<button id="underline">下划線</button>
<button id="hiliteColor">背景色</button>
<button id="save">上傳</button>
</div>
<div id="box" style="height: 300px;width: 400px;border: 1px solid black">
</div>
<script language="javascript">
window.onload=function(){
var editor,butGroup, doc,box;
editor = document.getElementById("HtmlEdit").contentWindow;//獲取iframe Window 對象
doc = document.getElementById("HtmlEdit").contentDocument; //獲取iframe documen 對象
butGroup = document.getElementById('butGroup');
box= document.getElementById('box');
//設置事件監聽
butGroup.addEventListener('click',function(e){
//通過e 事件 獲取點擊的標簽 id
switch (e.target.id){
case 'bold':addBold(); break;
case 'big':big(); break;
case 'copy':copy(); break;
case 'italic':italic();break
case 'hiliteColor':hiliteColor(); break;
case 'underline':underline();break;
case 'save':save();break
}
})
//只需鍵入以下設定,iframe立刻變成編輯器。
editor.document.designMode = 'On'; //打開設計模式
editor.document.contentEditable = true;// 設置元素為可編輯
function big(){
//所有字體特效只是使用 execComman() 就能完成。
editor.document.execCommand("fontSize", true, 10);
console.log( doc.body.innerHTML);
}
//復制方法
function copy(){
editor.document.execCommand("copy", true, null);
}
//加粗方法
function addBold() {
editor.document.execCommand("Bold", true, null);
}
//斜體方法
function italic(){
editor.document.execCommand('italic',true,null)
}
//加背景色
var hiliteColor = ()=>{ editor.document.execCommand('hiliteColor',true,'yellow') } //ES6 的箭頭函數寫法
//加下划線方法
var underline= ()=>{ editor.document.execCommand('underline',true,null)} //ES6 的箭頭函數寫法
//上傳方法
function save(){
box.innerHTML=doc.body.innerHTML;
}
}
</script>
</body>
</html>
5.參考
更多詳情及命令:https://developer.mozilla.org/zh-CN/docs/Web/API/Document/execCommand
