我有以下标记:
<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
的{{1}}伪类?点击.element
时没有运气,尝试e.stopPropogation()
。
demo
答案 0 :(得分: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')
});
答案 1 :(得分:1)
父母如何引入额外的课程,例如allow-active
<div class="parent allow-active">
然后修改你的css,.parent:active
成为
.parent.allow-active:active {
background:green;
}
意味着只有div同时具有parent
和allow-active
类
然后用一些jQuery来切换allow-active
类
$('.element').mousedown(function(e){
$('.parent').removeClass('allow-active');
}).mouseup(function(e){
$('.parent').addClass('allow-active');
});
答案 2 :(得分: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相同
答案 3 :(得分: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');
});