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})`;
    }
  • 相关阅读:
    网页设计~老生常谈~浏览器兼容2个主要问题的解决
    谈谈网页功能测试
    从PMP学习中浅谈公司行政工作
    肉肉谈对需求设计的想法到底是功能驱动界面?还是界面驱动功能?
    jndi和rmi学习
    mysql赋值变量:=的使用
    用Cookies和HashTable制作购物车
    nginx实现简单的反向代理
    .net Form认证扩展保存 Object 类型
    基于Docker搭建私有镜像仓库
  • 原文地址:https://www.cnblogs.com/LilyLiya/p/14313065.html
Copyright © 2011-2022 走看看