當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


HTML DOM execCommand()用法及代碼示例

HTML DOM execCommand() 方法用於執行在用戶正在選擇的可編輯部分上指定的命令。應該首先將 document.design 屬性設置為具有可編輯部分。

用法

以下是 execCommand() 方法的語法 -

document.execCommand(command, showUI, value)

這裏的value是一些需要完成的特定命令,例如fontSize、forecolor等。showUI是一個布爾值,用於指定該值是否應該顯示。命令名是需要在可編輯部分執行的命令。

以下是命令參數的值 -

"backColor", "bold", "createLink", "copy", "cut", "defaultParagraphSeparator", "delete",
"fontName", "fontSize", "foreColor", "formatBlock", "forwardDelete", "insertHorizontalRule",
"insertHTML", "insertImage", "insertLineBreak", "insertOrderedList", "insertParagraph",
"insertText", "insertUnorderedList", "justifyCenter", "justifyFull", "justifyLeft",
"justifyRight", "outdent", "paste", "redo", "selectAll", "strikethrough", "styleWithCss",
"superscript", "undo", "unlink", "useCSS"

示例

讓我們看一個 execCommand() 方法的例子 -

<!DOCTYPE html>
<html>
<body ondblclick="changeText()">
<h1>execCommand() method example</h1>
<h3>double click on any text to change its fontsize and color</h3>
<p>Here is some text for being clicked upon. Some sample text is here too </p>
<script>
   document.designMode = "on";
   function changeText() {
      document.execCommand("fontSize",true,"20px");
      document.execCommand("backColor",true,"lightgreen");
      document.execCommand("foreColor",true,"blue");
}
</script>
</body>
</html>

輸出

這將產生以下輸出 -

雙擊頁麵上的某些文本,該特定文本的格式將發生變化 -

在上麵的例子中 -

我們首先將事件處理程序與雙擊事件的文檔正文相關聯。雙擊任何 body 子級時,它將執行 changeText() 方法。這裏的 body 子元素是 h1、h3 和 p 元素 -

<body ondblclick="changeText()">

我們首先將文檔設計模式設置為開啟,以便我們可以編輯我們的文檔。函數 changeText() 執行文檔的 execCommand() 方法並傳遞其參數,如 fontSize、backColor、foreColor 以及它們各自的值。這些值將應用於用戶雙擊的可編輯部分 -

Function changeText() {
document.execCommand("fontSize",true,"20px");
document.execCommand("backColor",true,"lightgreen");
document.execCommand("foreColor",true,"blue");

相關用法


注:本文由純淨天空篩選整理自AmitDiwan大神的英文原創作品 HTML DOM execCommand() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。