关于jquery点击放大缩小的代码

在下新手有个问题想请教一下,下面这个实现点击后放大缩小的代码,再点了.close的这个click之后应该是要回到宽200px;高80px;的大小,但点击之后缩小后又会再放大,是因为.close标签是.box的子元素,导致点了.close也等于点了.box,所以又在执行了.box的放大,是这样的吗?

$(document).ready(function(){
        $(".box").click(function(){
            $(this).animate({
                 width:"400px",
                 height:"300px"
            });
        });
        $(".close").click(function(){
                $(".box").animate({
                 width:"200px",
                 height:"80px"
                });
        });
    });

html的部分
<body>
    <header>
        <div class="box">
            contact 
            <a href="#" class="close">close</a>
        </div>
    </header>
</body>

css的部分
<style>
    header {
        width: 100%;
        height: 100%;
        background-color: aquamarine;
    }
    .box {
        width: 200px;
        height: 80px;
        line-height: 80px;
        text-align: center;
        background-color: blueviolet;
        position: fixed;
        right: 10px;
        top: 10px;
    }
</style>
阅读 3.4k
1 个回答

是,因为点了.close以后默认事件会冒泡到.box上。你可以用事件对象阻止事件冒泡:

$(document).ready(function(){
    $(".box").click(function(){
        $(this).animate({
            width:"400px",
            height:"300px"
        });
    });
    $(".close").click(function(event){
        event.stopPropagation(); //阻止事件冒泡
        $(".box").animate({
             width:"200px",
             height:"80px"
        });
    });
});

参考:

  1. jQuery文档 - event.stopPropagation()

  2. 事件模型 - 事件的传播