简体   繁体   中英

How to make a delay between capturing/bubbling phase

I'm learning event phasing of nested elements so I create small project. Codepen JS starts on 43rd line.

So here's simple nested divs.

<div id="zzz" class="thir">
  0
  <div id="xxx" class="thir">
    0
    <div id="sss" class="thir">
      0
    </div>
  </div>
</div>

And here what we do with them.

const ar2 = [zzz, xxx, sss];
ar2.map(e => {
  e.addEventListener('click', nestedClick, phase);
})

function nestedClick(e) {
  // e.stopPropagation();
  const meow = this;
  const prevColor = this.style.backgroundColor;
  this.style.backgroundColor = '#757575';
  window.setTimeout(() => { meow.style.backgroundColor = prevColor}, 500);
}

To visually show how capturing/bubbling works I'd like to change background color and set timeout on each step, wait until it's done and trigger next click with the same strategy.

But here I see after I click on any element event still goes through, changing color and forces all .setTimeout() like at the same time. How can I repair it?

Side question: why e.stopPropagation() works whether it's capturing or bubbling phase?

Thank you for attention!

You need to shift the start time of the timers. And for a flashing effect having a second timer would be good.

 let counter = 1; const ar2 = [...document.getElementsByClassName('thir')]; ar2.map(e => { e.addEventListener('click', nestedClick); e.addEventListener('mouseup', function() { counter = 1; }); }); function nestedClick(e) { const prevColor = this.style.backgroundColor; debugger; setTimeout( () => { this.style.backgroundColor = '#757575'; setTimeout( () => { this.style.backgroundColor = prevColor; }, 50 * (counter++)); }, 500 * (counter++)); }
 <div id="zzz" class="thir"> CLICK ME <div id="xxx" class="thir"> CLICK ME <div id="sss" class="thir"> CLICK ME </div> </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM