【问题标题】:Chrome appears to ignore user-select in a contenteditable divChrome 似乎忽略了 contenteditable div 中的用户选择
【发布时间】:2016-10-21 04:25:16
【问题描述】:

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

显而易见的解决方案似乎是使用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;
}
<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>

有没有办法让它在 Chrome 中也能正常工作,或者这是一个无法克服的限制?

【问题讨论】:

  • 也适用于input[type=text],我想也适用于其他input[types]

标签: html css cross-browser contenteditable


【解决方案1】:

我也遇到了这个问题,并找到了一份体面的工作。它不漂亮,但它通常可以完成工作。

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

这样做的主要缺点(除了必须修改 HTML)是,如果在包装 div 上添加 contenteditable="false",那么它的所有子项也将变为不可编辑。您可以进一步嵌套另一个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;
}
<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>

【讨论】:

  • 洞察为什么 Chrome 可能会忽略 user-select:none; on editable... 从规范中:如果元素是可编辑元素,则计算值为 contain跨度>
  • 开发采用了另一条路径(使用不同的编辑器),所以我很难测试这是否有效......我接受答案,直至另行通知。
  • 这是一个好的开始,但不幸的是,您仍然可以从左侧或右侧删除整个&lt;span class="nope" contenteditable="false"&gt;Two&lt;/span&gt; 部分,但不能单独删除其内容。对于大多数用例来说,这可能是一个有问题的边缘案例
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-28
  • 2016-09-30
  • 2016-03-16
  • 2014-02-03
  • 2012-03-11
  • 2013-09-07
  • 2016-08-12
相关资源
最近更新 更多