美文网首页
事件(冒泡/委托)

事件(冒泡/委托)

作者: 智多牛 | 来源:发表于2016-12-19 10:46 被阅读0次
        <body>  
        
            <!-- 父对象 -->
            <div id="father">
                
                <!-- 子对象 -->
                <div id="son"></div>
                
            </div>
            
        </body>
        
        <style>
            
            #father
            {
                width: 200px;
                height: 200px;
                background-color: #000;
                
                overflow:hidden;
            }
            
            #son
            {
                width: 100px;
                height: 100px;
                margin: 50px 0px 0px 50px;
                background-color: #eee; 
            }
            
        </style>
        
        <script>
            
            /**
             * 冒泡:由目标节点,向父节点冒泡
             */
            var father = document.getElementById('father');
            
            var son    = document.getElementById('son');
            
            father.addEventListener('click',function(e)
            {
                console.log('father')
            })
            
            son.addEventListener('click',function(e)
            {
                console.log('son')
            })
            
            /**
             * 输出:son father
             */
            
            
            
            
            /**
             * 禁止冒泡
             */
            father.addEventListener('click',function(e)
            {
                console.log('father')
            })
            
            son.addEventListener('click',function(e)
            {
                console.log('son')
                
                e.stopPropagation();
            })
            
            /**
             * 输出:son
             */
            
            
            
            
            /**
             * 事件委托:在父对象上侦听所有子对象事件,并判断是哪个元素发出的
             */
            
            father.addEventListener('click',function(e)
            {
                console.log(e.target.id)  //输出:son
                
            })
            
        </script>

    相关文章

      网友评论

          本文标题:事件(冒泡/委托)

          本文链接:https://www.haomeiwen.com/subject/plxtvttx.html