CSS:阻止父元素获取:单击子元素时的活动伪类

kni*_*ion 30 html css html5 css3

的jsfiddle

单击时button,您会看到:active为父级触发了伪类div.是否存在纯CSS(或某些JS库)的:active伪类方式而不是在button点击时切换?

我试过了z-index,position: absolute & fixed没有成功.

Ami*_*mit 14

规格:

选择器不定义":active"或":hover"元素的父级是否也处于该状态.

这意味着它依赖于实现.如果一个实现选择以这种方式行事(正如当前浏览器显然那样),标准中没有任何内容可以改变它.

使用CSS4,您可能能够:

.parent:active:not(:has(:active)) {
   color: red;
}
Run Code Online (Sandbox Code Playgroud)

但这既不可用也没有最终确定.

  • 或者简单地使用标准样式覆盖div:active类.这样,div元素active不会改变.不是很优雅,但有效. (3认同)

MMa*_*gun 5

如果你真的想用CSS来解决这个问题只有

如果您的按钮是active,请添加一个:before-pseudo-element 并position: absolute;父项相同的背景之前提供 :before 。

button:active::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #eee;
    z-index: -1;
}
Run Code Online (Sandbox Code Playgroud)

现在所需要的是父级是:

position: relative;
z-index: 0;
Run Code Online (Sandbox Code Playgroud)

看看:http : //jsfiddle.net/s0at4w4b/4/

这并没有解决根本问题,但对于当前的问题的解决方案。


Ori*_*iol 5

我认为:has伪类永远不会在样式表中可用。如果浏览器最终决定实现它,它可能只适用于 JS API,例如querySelector.

不过,我的希望更大:focus-within,实现起来似乎更简单。

#parent:active:not(:focus-within) {
  background-color: red;
}
Run Code Online (Sandbox Code Playgroud)

当然,它只会阻止在单击按钮等可聚焦元素时:active应用。#parent您可以通过添加来使其他元素成为焦点tabindex = "-1"

遗憾的是,:focus-within它没有得到广泛支持,但您可以使用JS polyfill

#parent {
  border: 1px solid black;
  width: 300px;
  height: 300px;
}
#parent:active:not(.focus-within) {
  background-color: red;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://gist.githubusercontent.com/aFarkas/a7e0d85450f323d5e164/raw/"></script>
<div id="parent">
  <button>Click me</button>
  <p tabindex="-1">Or me</p>
</div>
Run Code Online (Sandbox Code Playgroud)

Github 不允许热链接,因此上面的代码片段可能无法工作,除非您将 polyfill 复制到您的服务器并使用它。