【问题标题】:ExecCommand in Meteor is not workingMeteor 中的 ExecCommand 不起作用
【发布时间】:2015-01-20 16:41:05
【问题描述】:

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

我的html:

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

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

【问题讨论】:

  • "null" 是错误的。它应该只是null,不带引号。但是,我不确定这会有什么不同。您的编辑器是否使用 iframe 作为编辑器内容?
  • 不,这没有任何区别。我以前也有它,我只是在测试它是否是因为我的 linter。我没有使用 iframe,而且我特别不想使用。
  • 好的。没有明显的原因为什么它不能工作。
  • 除了其他 ExecCommands 之外没有更多的代码与上述三个相同,但用于其他选项。我唯一遗漏的(我认为)是它在 if(Meteor.isClient) 块中运行。

标签: javascript meteor contenteditable rich-text-editor execcommand


【解决方案1】:

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

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

查看工作演示 here

代码示例,为清楚起见:

选项 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>

【讨论】:

  • 我在 div 中有 contenteditable="true"。它在上面的代码中。 -webkit-user-select: none;没用。
  • @mesosteros 查看我的编辑——我想我不清楚。我的意思是,如果您将contenteditable="true" 添加到可点击的div 元素(带有id 的元素)中,您会看到这些div 的文本上出现粗体——这意味着问题是execCommand 被吃掉了由那些divs 中的文字组成。解决方法是将div标签改为按钮或者使用css规则。
猜你喜欢
  • 1970-01-01
  • 2011-01-31
  • 1970-01-01
  • 2017-05-27
  • 1970-01-01
  • 1970-01-01
  • 2019-01-31
  • 1970-01-01
  • 2013-08-27
相关资源
最近更新 更多