1. 程式人生 > 實用技巧 >javascript阻止事件捕獲、預設事件和事件冒泡

javascript阻止事件捕獲、預設事件和事件冒泡

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>study</title>
</head>
<body>
<div class="out" oncontextmenu="myout(event)">
    <div class="center" oncontextmenu="mycenter(event,this)">
        <div class="in
"></div> </div> </div> <style> .out { width: 300px; height: 300px; background: red; } .center { width: 200px; height: 200px; background: yellow; } .in { width: 100px; height: 100px; background: green; }
</style> <script> function myout(ev) { console.log("外面的被點選了") ev.preventDefault()//阻止預設事件 } function mycenter(ev, obj) { if (ev.target == obj) {//阻止事件捕獲 console.log("中間的被點選了") ev.stopPropagation()//阻止事件冒泡 ev.preventDefault()//
阻止預設事件 } } </script> </body> </html>