HTML - DOM文件execCommand()方法



HTML DOM文件**execCommand()**方法用於在使用者選擇的可編輯區域執行指定的命令。文件的**document.designMode**屬性應設定為擁有文件中的可編輯區域。此方法現已**棄用**。

語法

document.execCommand(command, showUI, value);

引數

此方法接受三個引數,如下所示。

引數 描述
command 這是您想要在文件的可編輯區域執行的命令。以下是可執行命令的列表:
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
showUI 這是一個布林值,指定是否顯示 UI。
value 有些命令需要指定值。它儲存指定命令的值。

返回值

它返回一個布林值,對於支援的命令返回 true,對於不支援的命令返回 false。

HTML DOM文件'execCommand()'方法示例

以下示例說明了使用不同命令的execCommand()方法的使用。

更改字型大小和顏色

在以下示例中,字型顏色及其背景顏色以及字型大小會在雙擊時更改。

<!DOCTYPE html>
<html>
<head>
    <title>
        HTML DOM document execCommand() Method
    </title>
</head>
<body ondblclick="changeText()">
    <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, "5px");
            document.execCommand("backColor", true, "#04af2f");
            document.execCommand("foreColor", true, "white");
        }
    </script>
</body>
</html>

將句子加粗

在以下示例中,bold 命令用於在雙擊時將句子加粗。

<!DOCTYPE html>
<html>
<head>
    <title>
        HTML DOM document execCommand() Method
    </title>
</head>
<body ondblclick="changeText()">
    <h3>
        Double click on any text to change 
        its color and make it bold
    </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("backColor", true, "#04af2f");
            document.execCommand("foreColor", true, "white");
            document.execCommand("bold");
        }
    </script>
</body>
</html>

將句子居中對齊

在以下示例中,justifyCenter 命令在雙擊時使用。

<!DOCTYPE html>
<html>
<head>
    <title>
        HTML DOM document execCommand() Method
    </title>
</head>
<body ondblclick="changeText()">
    <h3>
        Double click on any text to make 
        it justifyCenter
    </h3>
    <p>Welcome to Tutorials Point...</p>
    <script>
        document.designMode = "on";
        function changeText() {
            document.execCommand("backColor", true, "#04af2f");
            document.execCommand("foreColor", true, "white");
            document.execCommand("justifyCenter");
        }
    </script>
</body>
</html>

支援的瀏覽器

方法 Chrome Edge Firefox Safari Opera
execCommand()
html_dom_document_reference.htm
廣告