javascript 仅为 div 设置 execcommand

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5205544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:21:43  来源:igfitidea点击:

set execcommand just for a div

javascriptexeccommand

提问by mkotwd

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

它有任何方法可以将 execcommand 与一个 div 元素绑定而不是整个文档,我试试这个:

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

but it has an error :

但它有一个错误:

execcommand is not a function

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

它有任何方法可以将 execcommand 与 div 元素而不是整个文档绑定!我不喜欢使用 iframe 方法。

回答by Tim Down

This is easier to do in IE than other browsers because IE's TextRangeobjects 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:

这在 IE 中比在其他浏览器中更容易做到,因为 IE 的TextRange对象有一个execCommand()方法,这意味着可以在文档的一部分上执行命令,而无需更改选择和临时启用designMode(这是您在其他浏览器中必须做的) )。这是一个可以干净利落地做你想做的事情的函数:

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);
    }
}

Examples:

例子:

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

回答by cabaret

Perhaps this helps you out:

也许这可以帮助你:

Example code 1on this page has the execcommand on a div by using a function. Not sure if that's what you're after? Good luck!

此页面上的示例代码 1通过使用函数在 div 上具有 exec 命令。不确定这是否是您所追求的?祝你好运!

Edit: I figured out how to put the code here :o

编辑:我想出了如何把代码放在这里:o

<head>
<script type="text/javascript">
    function SetToBold () {
        document.execCommand ('bold', false, null);
    }
</script>
</head>
<body>
      <div contenteditable="true" onmouseup="SetToBold ();">
       Select a part of this text!      
      </div>
</body>

回答by Hyman

Javascript:

Javascript:

var editableFocus = null;

  window.onload = function() {
    var editableElements = document.querySelectorAll("[contenteditable=true]");

    for (var i = 0; i<editableElements.length; i++) {
      editableElements[i].onfocus = function() {
        editableFocus = this.id;
      }
    };
  }

  function setPreviewFocus(obj){
    editableFocus = obj.id
  }

  function formatDoc(sCmd, sValue) {
    if(editableFocus == "textBox"){
      document.execCommand(sCmd, false, sValue); 
    }
  }

HTML:

HTML:

<div id="textBox" contenteditable="true">
Texto fora do box
</div>

<div contenteditable="true">
Texto fora do box
</div>

<button title="Bold" onclick="formatDoc('bold');">Bold</button>

回答by Jonny

You can keep it Simple, and add this to your div.

您可以保持简单,并将其添加到您的 div 中。

<div contenteditable="true" onmouseup="document.execCommand('bold',false,null);">