简体   繁体   English

如何使仅父div可点击?

[英]How to make only the parent div clickable?

As my title explains, how can I make only the parent-div clickable? 就像我的标题所解释的,如何才能仅使parent-div可点击?

HTML 的HTML

<div id="canvas" onclick="closeCanvas()">
    <img src="image.png" />
</div>

JQUERY JQUERY

function closeCanvas(){
    $("#canvas").fadeOut(300);
}

My issue is that when I click the "image", the function closeCanvas() is also trigged. 我的问题是,当我单击“图像”时,函数closeCanvas()也被触发。 How can I make only the parent, #canvas, triggerable? 如何仅使父级#canvas可触发?

Add StopPropagation to img that mean clicking the img will not pass the click event to the parent div: 将StopPropagation添加到img ,这意味着单击img不会将click事件传递给父div:

<div id="canvas" onclick="closeCanvas()">
   <img src="image.png" onClick="event.stopPropagation()" />
</div>

 $(document).ready(function(){ $('canvas').click(function(e){ console.log(e); }); }); function closeCanvas(event){ if(event.target.id== "canvas") $("#canvas").fadeOut(300); } 
 #canvas{ height:100px; width:100px; background-color:red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="canvas" onclick="closeCanvas(event)"> <img src="image.png" /> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM