如何只使父div可点击?

时间:2015-10-17 19:56:00

标签: jquery html

正如我的标题所解释的那样,如何才能使parent-div可点击?

HTML

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

JQUERY

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

我的问题是,当我点击“图像”时,函数closeCanvas()也会被触发。我怎样才能只生成#canvas,triggerable?

2 个答案:

答案 0 :(得分:3)

将StopPropagation添加到img,这意味着点击img不会将点击事件传递给父div:

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

答案 1 :(得分:3)

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