::selection 伪选择器忽略 ::before 伪元素

::selection pseudo selector ignoring ::before pseudo element

我正在使用 Clipboard.js 将 .container 的内容复制到用户的剪贴板。我已经设置了此 .container::selection / ::-moz-selection 的样式,它是子元素,因为在复制到剪贴板的过程中所有子元素都被 .select()ed。

除了 ::before(大概 ::after)伪元素外,它工作得很好。 ::before 或多或少忽略了我的 css 声明。我在 ::before 中使用 counter css 属性 作为 content.

这是暴露问题的片段。我没有包含任何 JS,因为没有必要暴露这个问题。单击并拖动代码块,您会看到 ::selection 上没有任何内容突出显示,除了 ::before 伪元素。

任何人都可以告诉我如何覆盖 ::before 伪元素的 ::selection 以使其不可见吗?

编辑:这似乎是一个 Safari/Chrome(大概是 -webkit- 问题)。在做了一些隔离测试后,在 Firefox 中没有发生。

.html.container {
 position: relative;
 display: block;
 padding: .9375rem .9375rem .9375rem 2.5rem;
 margin-bottom: 20px;
 background: rgba(38, 38, 38, .08);
 counter-reset: lines;
}
.html.container::before {
 content: '';
 position: absolute;
 top: 0;
    left: 0;
 width: 5px;
 height: 100%;
 background: grey;
}

.html.syntax {
 display: block;
 border-left: .0625rem solid black;
}

.html.syntax *::selection {
 background: transparent;
 color: inherit;
}

.html.syntax *::-moz-selection {
 background: transparent;
 color: inherit;
}

.html.line::before {
 content: counter(lines);
 position: absolute;
 left: 5px;
 width: 25px;
    color: grey;
 text-align: right;
 transition: all .25s ease;
}
.html.line {
 display: block;
 padding-left: 15;
 counter-increment: lines;
}

.html.line::before::selection {
 background: transparent;
 color: inherit;
}

.html.syntax::before::-moz-selection {
 background: transparent;
 color: inherit;
}
<div class="js html container" data-clipboard-target="#\<h1\>">
 <code class="html syntax" id="<h1>">
  <span class="html line">
   <span class="html comment">&lt;!-- Heading level 1 --&gt;</span>
  </span>
  <span class="html line">
   &lt;<span class="html tag">h1</span>&gt;Heading level 1&lt;<span class="html tag">/h1</span>&gt;
  </span>
 </code>
</div>

您可以在 "html line" 分类跨度上使用数据属性,这可以防止数字出现在 Chrome 的选择中。这样做的缺点是您将失去 auto-increment 行号的 CSS 计数器:

<div class="js html container" data-clipboard-target="#\<h1\>">
    <code class="html syntax" id="<h1>">
        <span class="html line" data-pseudo-content="1">
            <span class="html comment">&lt;!-- Heading level 1 --&gt;</span>
        </span>
        <span class="html line" data-pseudo-content="2">
            &lt;<span class="html tag">h1</span>&gt;Heading level 1&lt;<span class="html tag">/h1</span>&gt;
        </span>
    </code>
</div>

https://jsfiddle.net/ohyj81c4/

ref https://danoc.me/blog/css-prevent-copy/

你不能改变伪元素选择颜色的原因是因为你只能在一个选择器中使用 1 pseudo-element。 ::selection 和 ::before 都属于此定义,而不是 ::selection 是 pseudo-class,如 :active、:visited 等

参考:https://developer.mozilla.org/en/docs/Web/CSS/Pseudo-elements