Skip to content

Instantly share code, notes, and snippets.

@lymanlai
Created May 12, 2020 08:53
Show Gist options
  • Save lymanlai/ad1e0a8de97336fd734d5cd87ca4801b to your computer and use it in GitHub Desktop.
Save lymanlai/ad1e0a8de97336fd734d5cd87ca4801b to your computer and use it in GitHub Desktop.
MutationObserver
<html>
<style>
.outer {
padding: 20px;
background-color: aqua;
}
.inner {
padding: 40px;
background-color: black;
}
</style>
<body>
<div class="outer">
<div class="inner"></div>
</div>
<script>
// Let's get hold of those elements
var outer = document.querySelector('.outer');
var inner = document.querySelector('.inner');
// Let's listen for attribute changes on the
// outer element
new MutationObserver(function () {
console.log('mutate');
}).observe(outer, {
attributes: true
});
// Here's a click listener…
function onClick() {
let that = this.className
console.log(that, 'click');
setTimeout(function () {
console.log(that, 'timeout');
}, 0);
Promise.resolve().then(function () {
console.log(that, 'promise');
});
outer.setAttribute('data-random', Math.random());
}
// …which we'll attach to both elements
inner.addEventListener('click', onClick);
outer.addEventListener('click', onClick);
inner.click()
// 1. 输出什么?
// 2. 点击 inner 会输出什么?
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment