只为div设置execcommand [英] set execcommand just for a div

查看:224
本文介绍了只为div设置execcommand的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它可以用div元素绑定execcommand而不是整个文档,我可以这样尝试:

it has any way for bind execcommand with a div element not for whole document , i try this :

document.getElementById('div').execcommand(...)

但是有一个错误:

execcommand is not a function

它可以用div元素而不是整个文档来绑定execcommand! 我不喜欢使用iframe方法.

it has any way for bind the execcommand with just div element not whole document !! i don't like use iframe method .

推荐答案

在IE中,这比其他浏览器更容易完成,因为IE的

This is easier to do in IE than other browsers because IE's TextRange objects have an execCommand() method, meaning that a command can be executed on a section of the document without needing to change the selection and temporarily enable designMode (which is what you have to do in other browsers). Here's a function to do what you want cleanly:

function execCommandOnElement(el, commandName, value) {
    if (typeof value == "undefined") {
        value = null;
    }

    if (typeof window.getSelection != "undefined") {
        // Non-IE case
        var sel = window.getSelection();

        // Save the current selection
        var savedRanges = [];
        for (var i = 0, len = sel.rangeCount; i < len; ++i) {
            savedRanges[i] = sel.getRangeAt(i).cloneRange();
        }

        // Temporarily enable designMode so that
        // document.execCommand() will work
        document.designMode = "on";

        // Select the element's content
        sel = window.getSelection();
        var range = document.createRange();
        range.selectNodeContents(el);
        sel.removeAllRanges();
        sel.addRange(range);

        // Execute the command
        document.execCommand(commandName, false, value);

        // Disable designMode
        document.designMode = "off";

        // Restore the previous selection
        sel = window.getSelection();
        sel.removeAllRanges();
        for (var i = 0, len = savedRanges.length; i < len; ++i) {
            sel.addRange(savedRanges[i]);
        }
    } else if (typeof document.body.createTextRange != "undefined") {
        // IE case
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.execCommand(commandName, false, value);
    }
}

示例:

var testDiv = document.getElementById("test");
execCommandOnElement(testDiv, "Bold");
execCommandOnElement(testDiv, "ForeColor", "red");

这篇关于只为div设置execcommand的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆