`

execCommand method (document, TextRange, ...)

 
阅读更多

http://help.dottoro.com/ljcvtcaw.php

 

 

 

Allows running commands on certain objects.
The execCommand is one of the root methods of the rich-text editing feature of browsers.
The execCommand method works differently in different browsers, the commands are only executable for editable elements in Firefox, Google Chrome and Safari, while in Internet Explorer and Opera they can be used in editable and non-editable elements also.
An element can be made editable with the contentEditable property. If you want to make the entire document editable, use the designMode property or the contentEditable property for the body element. Note: Firefox only supports the contentEditable property from version 3.
The code generated by the execCommand method is different in browsers. Internet Explorer uses HTML tags, Firefox, Google Chrome and Safari generate inline styles and Opera sometimes uses HTML tags, sometimes styles.
For example, if the 'bold' command is executed on a non-bold text,
  • Internet Explorer and Opera generate a strong element around it,
  • Firefox, Google Chrome and Safari generate a span element around it and set the fontWeight style property of the span element to 'bold'. If an element exists around the non-bold text, then Firefox, Google Chrome and Safari set the fontWeight style property of this element to 'bold'.
If the 'bold' command is executed on a bold text, browsers remove the specified style property and/or the element including the text.
It can cause a problem if the execCommand method is executed on content that was previously generated by another browser. For example, in case of forums when the author tries to edit his/her post in a different browser than it was previously sent from. In that case, for example, if the 'bold' command is executed in Internet Explorer on a bold text that was previously created by the execCommand method in Firefox, then Internet Explorer cannot remove the bold style.
Example 4 shows a solution in Firefox, Opera, Google Chrome and Safari for changing the color of the selected text. Other text manipulation methods can be implemented similarly.
Use the queryCommandSupported method to detect whether a command is supported by the execCommand method. The use of a non-supported command for the execCommand method raises an exception.

Syntax:

object.execCommand (commandIdentifier, userInterface, value);
You can find the related objects in the Supported by objects section below.

Parameters:

commandIdentifier
         
Required. A case-insensitive string that specifies the name of the command. See command identifiers for more information.
userInterface
         
Required in Firefox and Opera, optional in Internet Explorer, Google Chrome and Safari. Boolean that indicates whether a user interface needs to be displayed or not.
One of the following values:
false
         
Default. Does not display a user interface.
true
         
Displays a user interface, if any.
value
         
Required in Firefox and Opera, optional in Internet Explorer, Google Chrome and Safari. Specifies a parameter value for the command. The possible values depend on the command. Use null if no value is needed.

Return value:

Boolean. One of the following values:
false There was an error while processing the command.
true The command was successful.

Example HTML code 1:

This example illustrates the use of the execCommand method:
 
<head><scripttype="text/javascript">function SetToBold () {
            document.execCommand ('bold', false, null);
        }
    </script></head><body><divcontenteditable="true"onmouseup="SetToBold ();">Select a part of this text!</div></body>
Did you find this example helpful? yes no

Example HTML code 2:

This example implements the previous example so that it works in older browsers as well:
  Code   editable.htm  
<head><scripttype="text/javascript">var editorDoc;
        function InitEditable () {
            var editor = document.getElementById ("editor");
            editorDoc = editor.contentWindow.document;          
            var editorBody = editorDoc.body;

                // turn off spellcheck
if ('spellcheck'in editorBody) {    // Firefox
                editorBody.spellcheck = false;
            }

            if ('contentEditable'in editorBody) {
                    // allow contentEditable
                editorBody.contentEditable = true;
            }
            else {  // Firefox earlier than version 3
if ('designMode'in editorDoc) {
                        // turn on designMode
                    editorDoc.designMode = "on";                
                }
            }
        }

        function ToggleBold () {
            editorDoc.execCommand ('bold', false, null);
        }
    </script></head><bodyonload="InitEditable ();">
    First, write and select some text in the editor.
    <br/><iframeid="editor"src="editable.htm"></iframe><br/><br/>
    You can toggle the bold/normal state of the selected text with this button:
    <br/><buttononclick="ToggleBold ();">Bold</button></body>
Did you find this example helpful? yes no

Example HTML code 3:

This example implements a simple WYSIWYG (What You See Is What You Get) editor:
  Code   editable.htm  
<head><scripttype="text/javascript">var editorDoc;
        function InitEditable () {
            var editor = document.getElementById ("editor");

            if (editor.contentDocument)
                editorDoc = editor.contentDocument;
            else
                editorDoc = editor.contentWindow.document;
            
            var editorBody = editorDoc.body;

                // turn off spellcheck
if ('spellcheck'in editorBody) {    // Firefox
                editorBody.spellcheck = false;
            }

            if ('contentEditable'in editorBody) {
                    // allow contentEditable
                editorBody.contentEditable = true;
            }
            else {  // Firefox earlier than version 3
if ('designMode'in editorDoc) {
                        // turn on designMode
                    editorDoc.designMode = "on";                
                }
            }
        }

        function ToggleBold () {
            editorDoc.execCommand ('bold', false, null);
        }
        function ToggleItalic () {
            editorDoc.execCommand ('italic', false, null);
        }
        function SetRed () {
            editorDoc.execCommand ('foreColor', false, "#ff0000");
        }
        function Delete () {
            editorDoc.execCommand ('delete', false, null);
        }
    </script></head><bodyonload="InitEditable ();">
    First, write and select some text in the editor.
    <br/><iframeid="editor"src="editable.htm"></iframe><br/><br/>
    You can use the following buttons to change the appearance of the selected text:
    <br/><br/><buttononclick="ToggleBold ();">Bold</button><buttononclick="ToggleItalic ();">Italic</button><buttononclick="SetRed ();">Set to red</button><buttononclick="Delete ();">Delete</button></body>
Did you find this example helpful? yes no

Example HTML code 4:

This complex example modifies the color of the selected text in Firefox, Opera, Google Chrome, Safari and Internet Explorer from version 9, similarly to the execCommand when it is invoked with the 'ForeColor' command. The example uses the selectionRange and Range objects to implements this functionality. The advantage of this solution is the browser-independently generated HTML code.
 
<head><scripttype="text/javascript">function GetNextLeaf (node) {
            while (!node.nextSibling) {
                node = node.parentNode;
                if (!node) {
                    return node;
                }
            }
            var leaf = node.nextSibling;
            while (leaf.firstChild) {
                leaf = leaf.firstChild;
            }
            return leaf;
        }

        function GetPreviousLeaf (node) {
            while (!node.previousSibling) {
                node = node.parentNode;
                if (!node) {
                    return node;
                }
            }
            var leaf = node.previousSibling;
            while (leaf.lastChild) {
                leaf = leaf.lastChild;
            }
            return leaf;
        }

            // If the text content of an element contains white-spaces only, then does not need to colorize
function IsTextVisible (text) {
            for (var i = 0; i < text.length; i++) {
                if (text[i] != ' ' && text[i] != '\t' && text[i] != '\r' && text[i] != '\n')
                    returntrue;
            }
            returnfalse;
        }

        function ColorizeLeaf (node, color) {
            if (!IsTextVisible (node.textContent))
                return;
            
            var parentNode = node.parentNode;
                // if the node does not have siblings and the parent is a span element, then modify its color
if (!node.previousSibling && !node.nextSibling) {
                if (parentNode.tagName.toLowerCase () == "span") {
                    parentNode.style.color = color;
                    return;
                }
            }

                // Create a span element around the node
var span = document.createElement ("span");
            span.style.color = color;
            var nextSibling = node.nextSibling;
            parentNode.removeChild (node);
            span.appendChild (node);
            parentNode.insertBefore (span, nextSibling);
        }

        function ColorizeLeafFromTo (node, color, from, to) {
            var text = node.textContent;
            if (!IsTextVisible (text))
                return;
            
            if (from < 0)
                from = 0;
            if (to < 0)
                to = text.length;

            if (from == 0 && to >= text.length) {
                    // to avoid unnecessary span elements
                ColorizeLeaf (node, color);
                return;
            }

            var part1 = text.substring (0, from);
            var part2 = text.substring (from, to);
            var part3 = text.substring (to, text.length);

            var parentNode = node.parentNode;
            var nextSibling = node.nextSibling;

            parentNode.removeChild (node);
            if (part1.length > 0) {
                var textNode = document.createTextNode (part1);
                parentNode.insertBefore (textNode, nextSibling);
            }
            if (part2.length > 0) {
                var span = document.createElement ("span");
                span.style.color = color;
                var textNode = document.createTextNode (part2);
                span.appendChild (textNode);
                parentNode.insertBefore (span, nextSibling);
            }
            if (part3.length > 0) {
                var textNode = document.createTextNode (part3);
                parentNode.insertBefore (textNode, nextSibling);
            }
        }

        function ColorizeNode (node, color) {
            var childNode = node.firstChild;
            if (!childNode) {
                ColorizeLeaf (node, color);
                return;
            }

            while (childNode) {
                    // store the next sibling of the childNode, because colorizing modifies the DOM structure
var nextSibling = childNode.nextSibling;
                ColorizeNode (childNode, color);
                childNode = nextSibling;
            }
        }

        function ColorizeNodeFromTo (node, color, from, to) {
            var childNode = node.firstChild;
            if (!childNode) {
                ColorizeLeafFromTo (node, color, from, to);
                return;
            }

            for (var i = from; i < to; i++) {
                ColorizeNode (node.childNodes[i], color);
            }
        }

        function ColorizeSelection (color) {

            if (window.getSelection) {  // all browsers, except IE before version 9
var selectionRange = window.getSelection ();

                if (selectionRange.isCollapsed) {
                    alert ("Please select some content first!");
                }
                else {
                    var range = selectionRange.getRangeAt (0);
                        // store the start and end points of the current selection, because the selection will be removed
var startContainer = range.startContainer;
                    var startOffset = range.startOffset;
                    var endContainer = range.endContainer;
                    var endOffset = range.endOffset;
                        // because of Opera, we need to remove the selection before modifying the DOM hierarchy
                    selectionRange.removeAllRanges ();
                    
                    if (startContainer == endContainer) {
                        ColorizeNodeFromTo (startContainer, color, startOffset, endOffset);
                    }
                    else {
                        if (startContainer.firstChild) {
                            var startLeaf = startContainer.childNodes[startOffset];
                        }
                        else {
                            var startLeaf = GetNextLeaf (startContainer);
                            ColorizeLeafFromTo (startContainer, color, startOffset, -1);
                        }
                        
                        if (endContainer.firstChild) {
                            if (endOffset > 0) {
                                var endLeaf = endContainer.childNodes[endOffset - 1];
                            }
                            else {
                                var endLeaf = GetPreviousLeaf (endContainer);
                            }
                        }
                        else {
                            var endLeaf = GetPreviousLeaf (endContainer);
                            ColorizeLeafFromTo (endContainer, color, 0, endOffset);
                        }

                        while (startLeaf) {
                            var nextLeaf = GetNextLeaf (startLeaf);
                            ColorizeLeaf (startLeaf, color);
                            if (startLeaf == endLeaf) {
                                break;
                            }
                            startLeaf = nextLeaf;
                        }
                    }
                }
            }
            else {
                    // Internet Explorer before version 9
alert ("Your browser does not support this example!");
            }
        }
    </script></head><body>
    Select some content on this page and use the buttons below to colorize the selected text.<br/><br/><buttononclick="ColorizeSelection ('#FF0000');">Set color to red!</button><buttononclick="ColorizeSelection ('#0000FF');">Set color to blue!</button><br/><div>Some text for selection</div><div><b>Some bold text for selection.</b></div></body>
Did you find this example helpful? yes no

Supported by objects:

Related pages:

External links:

分享到:
评论

相关推荐

    document.execCommand()的用法

    ### document.execCommand()详解 `document.execCommand()`是HTML文档对象模型(DOM)中的一个方法,用于执行浏览器的编辑命令,这些命令可以控制文本样式、布局、剪贴板操作等。此方法在早期的Web开发中被广泛使用...

    html中的内容直接下载到excel中,替换 document.execCommand(‘saveAs’)方法

    传统的做法是使用`document.execCommand('saveAs')`方法,但这个方法在某些现代浏览器中已被废弃,因此需要寻找替代方案。本篇文章将详细探讨如何在不依赖`execCommand('saveAs')`的情况下,实现HTML内容直接下载到...

    document.execCommand()解析

    《document.execCommand()解析》 在前端开发中,我们经常需要与用户进行交互,比如编辑文本、复制粘贴等操作。这些操作在浏览器环境中可以通过`document.execCommand()`方法实现。这个函数是HTML5引入的一个非常...

    javascript 常用方法及技巧

    document.execCommand 窗体COOKIE document.cookie 菜单事件 document.oncontextmenu 创建元素 document.createElement("SPAN"); 根据鼠标获得元素: document.elementFromPoint(event.x,event.y).tagName==...

    超级JS代码实例大全

    事件源对象 event.srcElement.tagName event.srcElement.type 捕获释放 event.srcElement.setCapture(); event.srcElement.releaseCapture();...document.execCommand 窗体COOKIE document.cookie 菜单事件

    javascript document.execCommand() 常用解析

    在Web前端开发中,`document.execCommand`是一个比较老的、即将被废弃的API,它允许执行一些命令来改变文档内容的外观或行为。在HTML5中,这种方式不再推荐使用,但对于旧版本的浏览器仍有必要了解这些命令的使用...

    document.execCommand()的用法小结

    首先要说明的是在firefox下支持不好。2D-Position 允许通过拖曳移动绝对定位的对象。 AbsolutePosition 设定元素的 position 属性为“absolute”(绝对)。 BackColor 设置或获取当前选中区的背景颜色。...

    document.selection.createRange方法与实例

    配合 execCommand,在 HTML 编辑器中很有用,比如:文字加粗、斜体、复制、粘贴、创建超链接等。 哈哈。我们都是新生来得。大家都来相互帮助呀。这样我们才能进步,我们才能赚大钱! [Ctrl+A 全选 注:如需引入...

    javascript-document对象详解(下).zip

    首先,`29.document-fun.html`可能是一个包含实际代码示例的HTML文件,它展示了`document`对象在实践中的用法。在HTML文档中,`document`对象允许我们访问和操作DOM(文档对象模型)。例如,我们可以使用`document....

    java代码大全

    document.execCommand • 窗体COOKIE document.cookie • 菜单事件 document.oncontextmenu • 创建元素 document.createElement("SPAN"); • 根据鼠标获得元素: document.elementFromPoint(event.x,event....

    IE图片缓存document.execCommand(&quot;BackgroundImageCache&quot;,false,true)

    为了解决这个问题,Erik发现了一个简单的方法,利用`document.execCommand`这个命令,结合特定的参数,可以强制IE6缓存背景图片。具体代码如下: ```javascript document.execCommand("BackgroundImageCache", ...

    HTML_Button[1].onclick_事件汇总

    这些操作都是通过调用 document 对象的 execCommand 方法来实现的。 4. 其他类 * window.location="view-source:" + window.location.href:查看源文件 * window.external.ShowBrowserUI('LanguageDialog', null)...

    document对象execCommand的command参数介绍

    2D-Position 允许通过拖曳移动绝对定位的对象。 AbsolutePosition 设定元素的 position 属性为“absolute”(绝对)。 BackColor 设置或获取当前选中区的背景颜色。 BlockDirLTR 目前尚未支持。...

    【JavaScript源代码】js实现复制粘贴的两种方法.docx

    这种方法利用了`document.execCommand`API,它允许执行一系列编辑命令(如复制、剪切等)。此API已经被浏览器逐步弃用,但在某些情况下仍可使用。以下是具体实现步骤: 1. **创建一个隐藏的输入框**:用于放置待...

    JS实现复制功能

    然后,调用`document.execCommand('copy')`命令来执行浏览器内置的复制功能,将选定的文本复制到剪贴板。最后,弹出一个警告框告知用户“复制成功”。 这个实现依赖于浏览器的`execCommand`方法,它是一个非标准但...

    在JavaScript中如何解决用execCommand(

    通过创建一个新的空白窗口,将需要保存的内容写入到这个窗口的document中,并执行execCommand("SaveAs")来触发保存动作。如果浏览器支持,这将保存文件到本地。 然而,由于现代浏览器(如Chrome, Firefox, Safari等...

    input按钮onclick事件大全

    - **`document.execCommand('FontSize',false,fs)`**:改变选中文本的字体大小。 这些命令主要用于富文本编辑器中,使得用户能够轻松地编辑和格式化文本内容。 #### 结论 通过上述介绍可以看出,`&lt;input&gt;`按钮...

    类似qq空间中的留言编辑器

    case 1: E.document.execCommand("Bold");break; case 2: E.document.execCommand("Italic");break; case 3: E.document.execCommand("Underline");break; case 6: var _Text=RemoveHTML(_Text); _Text=window....

    vb6_Webbrowser控件使用技巧

    - 通过`WebBrowser1.Document.parentWindow`获取当前文档的父窗口对象。 - 使用`navigator`属性获取浏览器的信息对象。 - 通过`oNav.userAgent`获取并打印浏览器的用户代理字符串(即用户代理标识符,用来表示...

Global site tag (gtag.js) - Google Analytics