如何使用javascript execCommand创建富文本编辑器? 第一第二第三

我已经创建了HTML和javascript文件。我在fontawesome.com中添加了一个粗体图标,并使用该图标制作了一个按钮。我使用execCommand尝试使加粗按钮在单击按钮后在文本区域中编辑选定的文本。但是代码不起作用。

<html>
    <head>
      <title>
          Editor
      </title>
      <link rel="stylesheet" href="stylesheet.css">
      <script src="script.js"> </script>
      <script src="https://kit.fontawesome.com/f7ac85e141.js" crossorigin="anonymous"></script>
    </head>
    <body>
        <header>
            <div class="navBar" id="heading-container" contentEditable="true">
                <button onclick="execCmd('bold');">
                    <i class="fas fa-bold"></i>
                </button>
            </div>
        </header>
        <textarea id="myTextArea"> Lorem ipsum dolor sit amet,consectetur. </textarea>
    </body>
</html>
function execCmd(command) {
  let field = document.getElementById('myTextArea');
  field.document.execCommand(command,false,null);
}

hf226 回答:如何使用javascript execCommand创建富文本编辑器? 第一第二第三

document.execCommand在contenteditable中使用,而不在文本区域中使用,所以:

function execCmd(command) {
  let field = document.getElementById('heading-container');
  field.document.execCommand(command,false,null);
}

btw execcommand已过时,因此请尝试使用范围替换它。或者您可以在这种情况下使用纯dom,就像@Mike Poole的答案一样。

,

您似乎打算以复杂的方式使文本加粗。我将使用getElementById方法进行处理:

function makeBold(){
  document.getElementById('myTextArea').style.fontWeight = '900';
}
<html>
    <head>
      <script src="https://kit.fontawesome.com/f7ac85e141.js" crossorigin="anonymous"></script>
    </head>
    <body>
          <div class="navBar" id="heading-container" contentEditable="true">
              <button onclick="makeBold();">
                  <i class="fas fa-bold"></i>
              </button>
          </div>
        <textarea id="myTextArea"> Lorem ipsum dolor sit amet,consectetur. </textarea>
    </body>
</html>

,

编辑

我决定查看the spec,以查看它是否专门说它不应该在textarea上运行,并且看起来您可能不想使用execCommand是因为规格顶部的警告:

  

此规范不完整,预计不会超出草案状态。作者不应直接使用其中的大多数功能,而应使用JavaScript编辑库。用户代理不能一致或完全实现本文档中描述的功能,并且预计在可预见的将来这种情况不会改变。当前,除了与剪贴板内容相关的某些execCommand动作外,别无选择,而且contentEditable = true通常用于绘制插入符号,并沿块方向以及一些较小的子点移动插入符号。该规范旨在帮助实现标准化这些现​​有功能的实现。预计将来,这两个规范都将由Content Editable和Input Events取代。

以下原始内容:


您的版本无法正常工作的原因有很多。

第一

field没有document属性,如果您在浏览器控制台中查看,将会看到类似field.document is undefined的内容。您只需要使用document.execCommand,其中document是全局文档对象。

如果需要,可以在可编辑文本周围使用iframe标签。这样iframe将具有contentDocument属性。我看不出这样做的充分理由。

第二

您需要通过删除选择的按钮来阻止onmousedown事件的默认操作。

<button onmousedown="event.preventDefault();" onclick="execCmd('bold');">
    <i class="fas fa-bold"></i>
</button>

第三

它似乎仍无法在textarea上运行,我不确定为什么。我在上面链接的document.execCommand页面上有link to an example使用execCommand,其中包含“粗体”。他们使用在其上设置了div的{​​{1}}。我让它自己与其中之一一起工作,但是contentEditable="true"仍然无法正常工作。也许还有其他事件需要停止?不知道。

本文链接:https://www.f2er.com/3100567.html

大家都在问