无法在 Shadow DOM 中跨元素选择文本

问题描述 投票:0回答:1

我目前正在使用属性 contenteditable=true 的自定义元素。

但是,我遇到了 Shadow DOM 的问题,因为它似乎阻止我跨多个元素选择文本。

我正在寻求深入了解这种行为的根本原因以及解决该问题的任何潜在方法。有人能解释一下吗?

预先感谢您的协助!

你尝试过什么:我完全不知道

您期望发生的情况:跨元素选择文本

实际结果:在 CodePen 上查看这个示例

<div class="content" contenteditable>
  <p>Why am I unable to use the mouse to select 'hello' and 'world'?</p>
  
  <c-text>
    <p>hello</p>
    <p>world</p>
  </c-text>
</div>
const template = document.createElement('template');

template.innerHTML = `
    <style>
    div { border: 1px solid black; }
    </style>
    <div><slot></slot></div>
`;

window.customElements.define('c-text', class extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({mode: 'open'});
    this.shadowRoot.appendChild(template.content.cloneNode(true));
  }
});

contenteditable shadow-dom custom-element
1个回答
0
投票

最近 116.nnn 更新中出现的已知错误,Chromium 团队正在处理该问题:
https://bugs.chromium.org/p/chromium/issues/detail?id=1484447

您可以通过设置任何样式属性来将其粘贴(或WD40):

<c-text>
  <h1 contenteditable>I am fixed, edit me</h1>
</c-text>

<c-text nofix>
  <h1 contenteditable>I am not fixed, can't edit me</h1>
</c-text>

<script>
customElements.define('c-text', class extends HTMLElement {
  constructor() {
    super().attachShadow({mode:'open'}).innerHTML = "<slot></slot>";
  }
  connectedCallback() {
    if (this.hasAttribute("nofix")) return;

    // alas this line now has to go into all components using contenteditable
    this.querySelectorAll("[contenteditable]").forEach(e=>e.style.display=null);
    
  }
});
</script>

© www.soinside.com 2019 - 2024. All rights reserved.