1

I am trying to create a small 20x20px div box, that when clicked opens a 200x200px box located inside the first box:

HTML

<div id="container" style="width:20px; height:20px;">
    <div id="box" style="display:none;width:200px; height:200px;">
        <img src="example1.gif" />
        <img src="example2.gif" />
    </div>
</div>

Aim

My aim is to make it so when #container is clicked, #box is faded in. The user will then click an image inside this box and the #box will then fade out.

  1. #container clicked and #box fadeIn();
  2. Item in #box is clicked
  3. #box fadeOut()

To do this I am using the following jQuery:

$(document).on("click", "#container", function(){

    $("#box").fadeIn("fast");
});

$(document).on("mouseleave", "#box", function(){

    $("#box").fadeOut("fast");
});

$(document).on("click", "#box img", function(){

    // Do things, removed for example

    $("#box").fadeOut();        
});

What actually happens

At the moment it's not working though because this happens:

  1. Click #container
  2. #box fades in
  3. Click #box img
  4. // Do things, removed for example
  5. #box fades out
  6. #box fades in

Number 6. on the above list should not happen, the box should not fade back in.

I think the problem is with .on("click", "#container", function(){ this may be applying that code when #container #box img is clicked, how can I stop this?

Demo

http://jsfiddle.net/8FuBD/

4

2 回答 2

3

您需要使用event.stopPropagation()。该事件正在冒泡,导致 div 再次淡入。

$(document).on("click", "#box img", function(e){
    e.stopPropagation();
    // Do things, removed for example

    $("#box").fadeOut();        
});​

http://jsfiddle.net/ycpFL/

于 2012-10-23T17:54:50.933 回答
2

更改要使用的最后一部分,以event.stopPropagation使事件不会冒泡到#box元素。

$(document).on("click", "#box img", function(e){

    // Do things, removed for example
    e.stopPropagation();
    $("#box").fadeOut();        
});
于 2012-10-23T17:54:44.850 回答