2016-06-26 56 views
0

我想知道是否有可能同時點擊兩個div,即使一個在另一個後面。是否可以同時點擊div1和div2,而div2覆蓋?

如果我點擊紅色的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'); 

}); 
+1

是的它可能,只需將事件添加到'.box'而不是'.one'元素 –

+1

這是什麼問題? https://jsfiddle.net/hsh85/ow67aaz1/2/ – hsh

回答

0

只是試試這個

$(".one").click(function() { 
    alert('green Clicked'); 
}); 

$(".two").click(function() { 
    alert('red Clicked'); 
    $(".one").trigger("click"); 
}); 
1

你需要triggerclick事件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}
<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格是不可見的,但它一直clicking

感謝

1

我會用同樣的單擊處理兩個元素,如果需要測試targetcurrentTarget根據要求:

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

0

你可以簡單地觸發下面div的click事件,當上面的div的click事件是fir時編輯。比如,讓我們說班級「一」在上面。

$(".one").click(function() { 
    console.log('Green div is clicked'); 
    $(".two").trigger("click"); 
}); 
$(".two").click(function() { 
    console.log('Red div is clicked'); 
}); 
0

您可以使用jQuery的$(this)來實現相同。代碼可以進一步減少到.. $(".one,.two").click(function() { var x = $(this).prop('class'); alert('class '+x+ ' div is clicked'); });

相關問題