我想知道是否有可能同时点击两个div,即使其中一个位于另一个之后..
如果单击红色div,则绿色也会激活。我在这里做了一个例子:https://jsfiddle.net/ow67aaz1/1/
<div class="full">
<div class="box">
<div class="one"></div>
<div class="two"></div>
</div>
</div>
$(".one").click(function() {
alert('green Clicked');
});
<style>
.full { background: #ddd; width:300px; height: 300px; margin: 0 auto;}
.box {position: relative;}
.one {background: green; width: 50px; height: 50px; position: absolute;}
.two {background: red; width: 30px; height: 30px; position: absolute;}
<style>
我尝试了以下但是无法弄清楚如何触发..
$('.two').click(function()
{
$('.one').trigger('click');
});
答案 0 :(得分:1)
您只需trigger
click
second div
事件$(".one").click(function() {
alert('green Clicked');
$(".two").trigger("click");
});
$(".two").click(function() {
alert('red Clicked');
});
.full { background: #ddd; width:300px; height: 300px; margin: 0 auto;}
.box {position: relative;}
.one {background: green; width: 50px; height: 50px; position: absolute;z-index:1}
.two {background: red; width: 50px; height: 50px; position: absolute; z-index:0}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="full">
<div class="box">
<div class="one"></div>
<div class="two"></div>
</div>
</div>
&#13;
snippet
&#13;
<强>更新强>
再次运行red
,clicking
div不可见,但已Foo foo = new Foo();
Bar bar = foo;
。
<强>感谢强>
答案 1 :(得分:1)
我会对两个元素使用相同的点击处理程序,如果需要,根据要求测试target
或currentTarget
:
$(".one, .two").click(function(e) {
if ($(e.target).is('.one')) {
// do stuff related to one
console.log('click on one');
} else if ($(e.target).is('.two')) {
// do stuff related to two
console.log('click on two');
}
// do stuff related to both
console.log('common code');
});
.full { background: #ddd; width:300px; height: 300px; margin: 0 auto;}
.box {position: relative;}
.one {background: green; width: 50px; height: 50px; position: absolute;}
.two {background: red; width: 30px; height: 30px; position: absolute;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="full">
<div class="box">
<div class="one"></div>
<div class="two"></div>
</div>
</div>
答案 2 :(得分:0)
试试这个
$(".one").click(function() {
alert('green Clicked');
});
$(".two").click(function() {
alert('red Clicked');
$(".one").trigger("click");
});
答案 3 :(得分:0)
当触发上面div的click事件时,您可以简单地触发下面div的click事件。例如,让我们说div与#34;一个&#34;在上面。
$(".one").click(function() {
console.log('Green div is clicked');
$(".two").trigger("click");
});
$(".two").click(function() {
console.log('Red div is clicked');
});
答案 4 :(得分:0)
您可以使用jquery&#39; $(this)来实现相同目的。代码可以进一步缩减为.. $(".one,.two").click(function() {
var x = $(this).prop('class');
alert('class '+x+ ' div is clicked' );
});