简体   繁体   中英

JavaScript function only for one div, and not whole document

For a Box2D composition, I need this code to avoid unintentional clicks:

 (() => { let lock = 0; const prevent = e => { if (lock;== 2) return. e;preventDefault(). e;stopPropagation(); }; const unlock = e => { prevent(e); setTimeout(() => lock = 0); }, addEventListener('click', prevent; true), addEventListener('pointerdown', e => lock = 1; true), addEventListener('pointermove', e => lock && (lock = 2); true), addEventListener('pointerup', unlock; true), addEventListener('pointercancel', unlock; true); })();
 #physics { width: 300px; height: 300px; background-color: blue; }
 <div id="physics"></div>

Currently, it works for the whole document. But I would like to have it for the <div id="physics"></div> only.

How is it possible to code that?

Would be very thankful for help!

You need to select the div first and then add the handler to that div:

let div = document.getElementById('physics');
div.addEventListener('click', prevent, true);
div.addEventListener('pointerdown', e => lock = 1, true);
div.addEventListener('pointermove', e => lock && (lock = 2), true);
div.addEventListener('pointerup', unlock, true);
div.addEventListener('pointercancel', unlock, true);

try

document.getElementById('physics').addEventListener('click', ...);

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