事件委托小demo(jq版)

<style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }

        .box1 {
            width: 200px;
            height: 60px;
            background: #00A3AF;
        }

        .box2 {
            width: 200px;
            height: 200px;
            background: #ee6600;
            display: none;
        }
        body{height: 100%;}
    </style>
<div class="box">
    <a class="box1">啦啦啦</a>
    <div class="box2">我是展开的部分~~</div>
</div>
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
<script type="text/javascript">
    var $box1 = $('.box1');
    var $box2 = $('.box2');
    $('body').on('touchstart', function (e) {
        if (judgeCondition(e)) {
            // 如果点击的是按钮,或者展开的那个盒子,显示
            $box2.show();
        } else {
            // 否则隐藏
            $box2.hide();
        }
    })
    function judgeCondition(e) {
        var $target = $(e.target);
        // 点击的是按钮
        if ($target.hasClass('box1')) {
            return true;
        }
        // 点击的是展开的那个盒子
        if ($target.closest('.box2').length) {
            return true;
        }
        return false;
    }
</script>

事件绑在body上
只有点击的按钮和展开区域本身不隐藏,否则都隐藏。
posted @ 2016-08-02 15:38  雪明瑶  阅读(375)  评论(0编辑  收藏  举报