Meteor中的ExecCommand不起作用

ExecCommand in Meteor is not working

本文关键字:不起作用 ExecCommand 中的 Meteor      更新时间:2023-09-26

我正在尝试在Meteor中实现ContentEditable的基本富文本编辑功能,但我在使用execCommand时遇到了问题。撤消和重做命令工作正常,但所有其他命令(如粗体和斜体)不起作用,并且不会给出任何错误。该代码作为常规页面也可以正常工作(我已经对 Meteor 进行了明显的改编,例如模板和事件)。

我的网页:

<body>
    {{> buttons}}
  <div id="editor" class="textZone" contenteditable="true"></div>
</body>
<template name="buttons">
    <div id="rtfOptions">
        <div class="separate">
            <div class="rtfOption" id="undo">undo</div>
            <div class="rtfOption" id="redo">redo</div>
        </div>
        <div class="separate">
            <div class="rtfOption" id="bold">bold</div>
            <div class="rtfOption" id="italic">italic</div>
        </div>
    </div>
</template>

我的事件(只有 2 个非工作 + 撤消。至于其余的几乎相同):

if (Meteor.isClient) {
        Template.buttons.events({
                "click #bold": function() { // Toggles bold on/off for the selection or at the insertion point
                    document.execCommand("bold", false, "null");
                },
                "click #italic": function() { // Toggles italics on/off for the selection or at the insertion point
                    document.execCommand("italic", false, "null");
                },
                "click #undo": function() { // Undoes the last executed command.
                    document.execCommand('undo', false, "null");
                }
    )};
}

有人知道这个问题吗?它与文档或范围有关吗?

如果您将div标签更改为button(对于可点击的元素),或者使div文本不可选择(例如使用css禁用user-select),它应该按预期工作。

原因是当你点击里面有文本的div时,execCommand会针对div的文本(不是contenteditable),所以命令会静默失败。尝试将contenteditable="true"添加到div中,如果您单击它,您将看到它将加粗div的文本。或者,尝试添加 css 规则-webkit-user-select: none;(在 Chrome 上,供应商前缀在其他浏览器上有所不同)以禁用div 上的文本选择,您将看到execCommand工作正常。

在此处查看工作演示。

为清楚起见,代码示例:

选项 1

<template name="buttons">
  <div id="rtfOptions">
    <div class="separate">
      <div class="rtfOption" id="bold" style="user-select: none; -webkit-user-select: none; -webkit-touch-callout: none;">bold</div>
    </div>
  </div>
</template>

选项 2

<template name="buttons">
  <div id="rtfOptions">
    <div class="separate">
      <button class="rtfOption" id="bold">bold</button>
    </div>
  </div>
</template>