是否可以禁用父元素的 :active 伪类?

5

我有以下标记:

<div class="parent">
  I should change my color to green when clicked
  <div class="element">I should do nothing when clicked</div>
</div>

这里是相关的CSS代码:
.parent {
  width:200px;
  height:200px;
  background: red;
  color: #fff;
}
.parent:active {
  background:green;
}
.element {
  background:blue;
}

有没有办法在点击.element时,防止触发.parent:active伪类?尝试了在.element被点击时使用e.stopPropogation(),但没有成功。 演示

2
我猜测 jQuery 中的 .stopPropagation() 方法对 CSS 渲染没有影响,只影响 JavaScript 事件。 - Linus Caldwell
4个回答

2
您可以直接使用jQuery替代:active,就像在这个演示(link)中一样。
$('.element').mousedown(function(e){
  e.stopPropagation();
});

$('.parent').mousedown(function(e){
  $('.parent').css('background', 'green')
    }).mouseup(function(e){
  $('.parent').css('background', 'red')
});

谢谢,这接近我现在的做法,直到我有更好的解决方案。 - Paul Kozlovitch

1

在父元素中加入一个额外的类,例如allow-active,怎么样?

<div class="parent allow-active">

然后修改你的 CSS,使得 .parent:active 变成:
.parent.allow-active:active {
    background:green;
}

这意味着只有当 div 同时具有 parentallow-active 类时,颜色才会改变。

然后使用一点 jQuery 来切换 allow-active 类。

$('.element').mousedown(function(e){
    $('.parent').removeClass('allow-active');
}).mouseup(function(e){
    $('.parent').addClass('allow-active');
});

0

可以用 JavaScript 实现

$(document).ready(function(){
    $(".parent").click(function(){
$(this).css("background","green")
    });
   $(".parent .element").click(function(e) {
       return false;
   });
});

还有 CSS

.parent {
  width:200px;
  height:200px;
  background: red;
  color: #fff;

}
.parent:active {

}
.element {
  background:blue;

}

HTML是相同的


0

Doorknob的替代方案是使用event.target

$('.parent').mousedown(function(e){
    if ($(e.target).is(this))
        $('.parent').css('background', 'green');
}).mouseup(function(e){
    if ($(e.target).is(this))
        $('.parent').css('background', 'red');
});

演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接