javascript execCommand,复文本框神器

35740次浏览

下面我们来介绍一下javascript execCommand方法,可以说javascript execCommand是复文本框必不可少的方法。今天上午的文章js复文本函数,是用自己封装的函数方法来写的,通常项目中一般不这么写,复文本加粗,倾斜,下划线,字体等等方法,大多是用document.execCommand方法。

下面对document.execCommand方法做一下简单介绍:

当document对象被转换为设计模式的时候(选中,设置contentEditable等),document对象提供了一个execCommand方法,通过给这个方法传递参数命令可以操作可编辑区域的内容。这个方法的命令大多数是对document选中区域的操作 (如bold, italics等), 也可以插入一个元素(如增加一个a链接) 或者修改一个完整行 (如缩进).。当元素被设置了contentEditable,通过执行execCommand 方法可以对当前活动元素进行很多操作。

语法

execCommand(String aCommandName, Boolean aShowDefaultUI, String aValueArgument)

参数

String aCommandName  //命令名称
Boolean aShowDefaultUI  // 是否展示用户界面,默认为false。Mozilla没有实现
String aValueArgument  // 一些命令需要一些额外的参数值(如insertimage需要提供这个image的url)。默认为null。

命令名称介绍(第一个参数)

backColor (用法:document.execCommand(”BackColor”,”false”,sColor); )
改变文档的背景颜色。 在styleWithCss模式,它影响的是包含元素的背景。 这个命令要求提供一个颜色值作为第三个参数 (Internet Explorer 使用这个命令设置文本背景色)
bold (用法: document.execCommand(”Bold”,”false”,null); )
对选中文本或者插入元素设置、取消粗体显示. (Internet Explorer 使用STRONG 标签 而不是 B标签。)
contentReadOnly
转化文档进入只读或者可编辑模式. 这个命令要求提供给一个boolean值给第3个参数(ie不支持)。
copy   用法:document.execCommand(”Copy”,”false”,null); 
把当前选中区域复制 到系统剪贴板。使用这个命令需要首先在 user.js 接口中进行激活。
createLink
当有选中区域的时候,使用这个命令转化选中区域为一个锚点,需要提供一个URI给第3个参数. 这个URI必须至少包含一个字符,空白字符也可。(Internet Explorer 会创建一个URI为空的a标签)
cut     用法:document.execCommand(”Cut”,”false”,null); 
剪切选中文本到剪切板. 同copy一样需要开启剪切板功能。
decreaseFontSize
给选中文本或者插入元素添加一个small标签。(Internet Explorer不支持)
delete
删除当前选中区域
enableInlineTableEditing
开启或禁用表的行和列的插入删除功能 ( Internet Explorer不支持)
enableObjectResizing
开启或禁用图片或者其他可resize元素的resize功能 ( Internet Explorer不支持)
fontName  用法:document.execCommand(”FontName”,”false”,sFontName); 
改变选中文本或者插入元素的字体。需要给第3个参数提供一个字体值
fontSize  用法:document.execCommand(”FontSize”,”false”,sSize|iSize); 
改变选中文本或者插入元素的字体大小。需要给第3个参数提供一个数字
foreColor
改变选中文本或者插入元素的字体颜色。需要给第3个参数提供一个颜色值

上面是最常用的命令,其他命令暂不列举!

看到上面的用法,大家心动了吧,我现在给大家举几个简单的例子:

demo1:

<head>
    <script type="text/javascript">
        function SetToBold () {
            document.execCommand ('bold', false, null);
        }
    </script>
</head>
<body>
    <div contenteditable="true" onmouseup="SetToBold ();">选择文本加粗,放开文本不加粗,哈哈哈,haorooms</div>
</body>

demo2, 用iframe方法,模仿编辑器

<head>
    <script type="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>
<body onload="InitEditable ();">
    首先在编辑器中选中文本
    <br />
    <iframe id="editor" src="editable.htm"></iframe>
    <br /><br />
    点击加粗,我会变粗,选中,点击加粗,我会不加粗!
    <br />
    <button onclick="ToggleBold ();">加粗</button>
</body>

editable.htm

<!DOCTYPE html>
<html>
<head>
    <title>Editable 例子</title>
    <meta charset="utf-8" />
</head>
<body>
   haorooms在编辑器中
</body>
</html>

demo3, 用iframe方法,模仿编辑器,用的是一个iframe啊,你可以复制上面的内容,代码如下,案例预览

<head>
    <script type="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>
<body onload="InitEditable ();">
    First, write and select some text in the editor.
    <br />
    <iframe id="editor" src="editable.htm"></iframe>
    <br /><br />
    You can use the following buttons to change the appearance of the selected text:
    <br /><br />
    <button onclick="ToggleBold ();">加粗</button>
    <button onclick="ToggleItalic ();">斜体</button>
    <button onclick="SetRed ();">红色</button>
    <button onclick="Delete ();">删除</button>
</body>

demo4,直接对文本进行操作,案例预览

<head>
    <script type="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')
                    return true;
            }
            return false;
        }

        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>
   用设置红色和蓝色的按钮,分别来操作文档中的文字哦!<br /><br />
    <button onclick="ColorizeSelection ('#FF0000');">设置红色</button>
    <button onclick="ColorizeSelection ('#0000FF');">设置蓝色</button>
    <br />
    <div>haorooms我是来呗选择的啊!</div>
    <div><b>我是来被加粗的啊!</b></div>
</body>

上面就是javascript execCommand 作为复文本框,是不是很强大啊!

相关文章: