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})`;
    }
  • 相关阅读:
    洛谷P1219 八皇后 我。。。。。。
    c++ STL map
    洛谷P1765 手机_NOI导刊2010普及(10) 关于cin和getline的一些区别 以及一些STL
    Restore the Permutation by Sorted Segments CodeForces
    Alternating Subsequence CodeForces
    cerr与cout
    (转)女生应该找一个玩ACM的男生
    (转)搞ACM的你伤不起
    c++多组数据输入
    不要62 HDU
  • 原文地址:https://www.cnblogs.com/LilyLiya/p/14313065.html
Copyright © 2011-2022 走看看