JS點擊子元素不觸發父元素點擊事件(js阻止冒泡)


<html>
<title></title>
<head>
    <meta charset="utf-8">
    <style type="text/css">
        .divone{width:100px;height:100px;background:black;position: relative;cursor: pointer}
        .divchild{position: absolute;margin:10px;width:50px;height:50px;background:white;cursor: pointer}
    </style>
    <script type="text/javascript">
        function divone(){ 
            //這里是divone事件的代碼 
            console.log('divone事件');
         
        } 
        
        function divchild(){
            //這里是divchild事件的代碼 
            console.log('divchild事件');
            stopPropagation();
        }

        function stopPropagation(e) {  
            e = e || window.event;  
            if(e.stopPropagation) { //W3C阻止冒泡方法  
                e.stopPropagation();  
            } else {  
                e.cancelBubble = true; //IE阻止冒泡方法  
            }  
        }
    </script>
</head>
<body>
    
    <div class="divone" onclick="divone(this)"> 
        
        <div class="divchild" onclick="divchild(this)"></div> 
        
    </div> 
 
</body>
</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM