[英]Is it possible to click div1 and div2 simultaneously, while div2 is overlaying?
我想知道是否可以同时单击两个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');
});
您只需要trigger
second div
的click
事件
$(".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}
<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>
更新资料
再次运行该snippet
, red
div不可见,但一直在clicking
。
谢谢
我将对两个元素使用相同的单击处理程序,并根据需要根据需要测试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>
尝试这个
$(".one").click(function() {
alert('green Clicked');
});
$(".two").click(function() {
alert('red Clicked');
$(".one").trigger("click");
});
当上方的div的click事件被触发时,您可以简单地触发下方的div的click事件。 例如,假设上面的类为“ one”的div。
$(".one").click(function() {
console.log('Green div is clicked');
$(".two").trigger("click");
});
$(".two").click(function() {
console.log('Red div is clicked');
});
您可以使用jquery的$(this)实现相同目的。 代码可以进一步简化为.. $(".one,.two").click(function() { var x = $(this).prop('class'); alert('class '+x+ ' div is clicked' ); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.