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})`;
    }
  • 相关阅读:
    【bzoj2653】【middle】【主席树+二分答案】
    Codeforces 464E. The Classic Problem
    关于主席树的入门,讲解和题单
    BZOJ3531-[Sdoi2014]旅行(树剖+线段树动态开点)
    [bzoj3123][洛谷P3302] [SDOI2013]森林(树上主席树+启发式合并)
    1018_两个圆相交的面积
    String对象中常用的方法
    张爱玲写的信
    React Native拆包及热更新方案 · Solartisan
    vue项目实战
  • 原文地址:https://www.cnblogs.com/LilyLiya/p/14313065.html
Copyright © 2011-2022 走看看