zoukankan      html  css  js  c++  java
  • Event bubbling

    stopPropagation() Event Method

    The stopPropagation() method prevents propagation of the same event from being called.

    Propagation means bubbling up to parent elements or capturing down to child elements.

    在我们的inline button例子中,button是p的孩子,button和p还是section的孩子,如果不使用stopPropagation()的话,如果点击button按钮,“button clicked”, “paragraph clicked”, “section clicked”会顺序出现。

    在changeColor button的例子中,加了stopPropagation(),所以点击按钮,只会触动产生随机背景颜色的function;

    如果不加这个的话,会接着触发container的toggle.hide操作。

    ——.hide在哪?

    ——html的style里面定义的

    <style>
    .hide {
    display: none;
    }
    </style>
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Bubbling</title>
    
        <style>
            .hide {
                display: none;
            }
        </style>
    </head>
    
    <body>
        <section onclick="alert('section clicked')">
            <p onclick="alert('paragraph clicked')">
                I am a paragraph:
                <button onclick="alert('button clicked')">Click</button>
            </p>
        </section>
    
        <div id="container">
            Click To Hide
            <button id="changeColor">Change Color</button>
        </div>
    
        <script src="app.js"></script>
    
    </body>
    
    </html>
    const button = document.querySelector('#changeColor');
    const container = document.querySelector('#container');
    
    button.addEventListener('click', function (e) {
        container.style.backgroundColor = makeRandColor();
        e.stopPropagation();
    })
    container.addEventListener('click', function () {
        container.classList.toggle('hide'); //隐藏显示,toggle,reverse current state
    })
    
    const makeRandColor = () => {
        const r = Math.floor(Math.random() * 255);
        const g = Math.floor(Math.random() * 255);
        const b = Math.floor(Math.random() * 255);
        return `rgb(${r}, ${g}, ${b})`;
    }
  • 相关阅读:
    python小程序之购物系统
    列表,元祖,字典的使用
    几个python小程序
    default
    RTTI
    man
    养喜神去杀机
    IDEA+Maven+Git
    入门
    CheckStyle简介
  • 原文地址:https://www.cnblogs.com/LilyLiya/p/14313065.html
Copyright © 2011-2022 走看看