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

时间:2017-01-23 12:25:08

标签: html css css-selectors cross-browser pseudo-element

我正在使用Clipboard.js将.container的内容复制到用户的剪贴板。我已将此::selection的{​​{1}} / ::-moz-selection设置为其子元素,因为在复制到剪贴板过程中所有子元素都为.container

除了.select()(以及可能是::before)伪元素之外,它的效果很好。 ::after或多或少忽略了我的css声明。我使用::before中的counter css属性作为::before

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

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

编辑:这似乎是Safari / Chrome(可能是::before问题)。在进行一些隔离测试后,Firefox中没有发生这种情况。

::before still being selected

-webkit-
.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;
}

1 个答案:

答案 0 :(得分:1)

您可以在“html line”分类范围内使用数据属性,这可以防止该数字出现在Chrome中的选择中。这样做的缺点是你将丢失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/

Lines with data-attributes selected on Chrome

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

无法更改伪元素选择颜色的原因是因为您只能在选择器中使用1个伪元素。两者:: selection和:: before都在这个定义之下,而不是:: selection是pseudo-class,如:active,:visited etc。

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

相关问题