Chrome似乎忽略了内容可编辑div中的用户选择

Sep*_*ram 3 html css cross-browser contenteditable

我需要使它成为contenteditablediv中的某些元素是不可选择的,以便用户在尝试将插入符号移动到它们所在的位置时将跳过它们。

显而易见的解决方案似乎是使用设置样式user-select: none。这在Firefox中确实可以很好地工作,但是不幸的是,在Google Chrome中完全无法使用。

.ok {
  -webkit-user-select: text;
     -moz-user-select: text;
      -ms-user-select: text;
          user-select: text;
}

.nope {
  -webkit-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
          user-select: none;
}
Run Code Online (Sandbox Code Playgroud)
<div contenteditable="true" readonly>
  <span class="ok">One</span><span class="nope">Two</span><span class="ok">Three</span>
  <div class="nope">
    <span class="ok">One</span><span class="nope">Two</span><span class="ok">Three</span>
  </div>
  <span class="nope">One</span><span class="ok">Two</span><span class="nope">Three</span>
  <div class="nope">
    <span class="nope">One</span><span class="ok">Two</span><span class="nope">Three</span>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

有没有办法使它在Chrome中也能正常工作,还是一个无法克服的局限性?

roa*_*ark 6

我也遇到了这个问题,并且找到了不错的解决方法。它虽然不漂亮,但通常可以完成工作。

如果添加contenteditable="false"沿user-select:none;则Chrome将正确处理CSS规则。这些元素将不再是可选的。

这样做的主要缺点(除了必须修改HTML之外)是,如果contenteditable="false"在包装div上添加了它,则其所有子元素也将变得不可编辑。您可以进一步嵌套另一个contenteditable="true",这将允许嵌套的内容是可编辑的,但是这样一来便无法从嵌套的内容中选择外部内容。

最终,当启用contenteditable时,在Chrome中正确实施CSS规则将是最佳解决方案。(由于用户选择规格,可能是有意的,请参阅下面的评论)

使用的解决方案示例contenteditable="false"(不在包装div上)。

.ok {
  -webkit-user-select: text;
  -moz-user-select: text;
  -ms-user-select: text;
  user-select: text;
}

.nope {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
Run Code Online (Sandbox Code Playgroud)
<div contenteditable="true" readonly>
  <span class="ok">One</span>
  <span class="nope" contenteditable="false">Two</span>
  <span class="ok">Three</span>
  <div>
    <span class="ok">One</span>
    <span class="nope" contenteditable="false">Two</span>
    <span class="ok">Three</span>
  </div>
  <span class="nope" contenteditable="false">One</span>
  <span class="ok">Two</span>
  <span class="nope" contenteditable="false">Three</span>
  <div>
    <span class="nope" contenteditable="false">One</span>
    <span class="ok">Two</span>
    <span class="nope" contenteditable="false">Three</span>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 深入了解为什么 Chrome 可能会在可编辑时忽略 `user-select:none;`... 根据规范:_如果元素是可编辑元素,则计算值是 `contain`_ (2认同)