document.execCommand() 是早期實作所見即所得編輯器與網頁操作的核心 API。以下整理它的可用指令,並附上幾個實際應用。開宗明義:它在 Firefox 下的支援度不佳,且現已被標記為不建議使用。
這類指令的共同語意是「用某個控制項覆蓋目前的選取區」:
利用 isNaN 判斷輸入是否為數值,若不是就執行 undo 把剛才的輸入還原:
<input type="text" name="text"
onkeyup="if(isNaN(value)) execCommand('undo')" />
這個技巧允許小數點,因此 1981.121 這類輸入可以通過。不過要注意 isNaN('') 為 false,空值不會被攔下來。
<input type="button" value="剪切" onclick="document.execCommand('Cut')">
<input type="button" value="拷貝" onclick="document.execCommand('Copy')">
<input type="button" value="粘貼" onclick="document.execCommand('Paste')">
<input type="button" value="撤消" onclick="document.execCommand('Undo')">
<input type="button" value="重做" onclick="document.execCommand('Redo')"
id="button2" name="button2">>
<input>
<input type="button" value="刪除" onclick="document.execCommand('Delete')">
<input type="button" value="黑體" onclick="document.execCommand('Bold')">
<input type="button" value="斜體" onclick="document.execCommand('Italic')">
<input type="button" value="下劃線" onclick="document.execCommand('Underline')">
<input type="button" value="停止" onclick="document.execCommand('stop')">
<input type="button" value="保存" onclick="document.execCommand('SaveAs')">
<input type="button" value="另存為" onclick="document.execCommand('Saveas', false, 'c:test.htm')">
<input type="button" value="字型" onclick="document.execCommand('FontName', false, fn)">
<input type="button" value="字型大小" onclick="document.execCommand('FontSize', false, fs)">
<input type="button" value="重新整理" onclick="document.execCommand('refresh', false, 0)">
execCommand 已被 MDN 明確標示為 deprecated,各瀏覽器的行為不一致,Firefox 長期支援不佳,Paste、SaveAs 這類涉及本機檔案與剪貼簿的指令更因安全性考量而多被禁用。
實務上的建議是:
navigator.clipboard.writeText()。<input type="number"> 或加上 pattern 與驗證邏輯,比攔截 keyup 再 undo 可靠得多。