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})`; }