2013-03-20 55 views
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; 
} 

有什么办法来防止触发.parent:active伪类被点击.element什么时候?尝试e.stopPropogation().element点击没有运气。 demo

+2

我猜测jQuery'.stopPropogation()'对css渲染没有影响,只是在JavaScript事件上。 – 2013-03-20 12:40:05

回答

2

您可以使用jQuery而不是:active,就像在这demo (link)

$('.element').mousedown(function(e){ 
    e.stopPropagation(); 
}); 

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

谢谢,我现在这样做很接近,直到我没有更好的解决方案。 – 2013-03-20 13:28:10

0

可能与JS

$(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

的替代解决方案门把手的将被使用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'); 
}); 

Demo

1

如何父引入额外的类如allow-active

<div class="parent allow-active"> 

然后修改你的CSS所以.parent:active成为

.parent.allow-active:active { 
    background:green; 
} 

这意味着如果只改变div有两个parentallow-active类的颜色

然后有点jQuery来切换allow-active class

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