简体   繁体   中英

How can I make the onMouseOver function run only once? | Html

I have a code when hovering over the button, it prints a letter on the website. How can I make this hovering happen only once? What I really want to do is hover then the function called a will only be performed once This is the code:

function a(){
document.body.innerHTML += 'uu';
}
</script>
<button onMouseOver="a()">hello world</button>

Rather than using the onmouseover attribute, attach the handler from Javascript and specify the once option:

 let count = 0; const a = function() { document.getElementById('btnTest').innerHTML = `Button hovered ${++count} times`; document.body.innerHTML += 'uu'; }; window.addEventListener('DOMContentLoaded', () => { document.getElementById('btnTest').addEventListener('mouseover', a, { once: true }); });
 <button id="btnTest">This is the button</button>

EventTarget.addEventListener() - Web APIs | MDN

Give your control an id to target, and then remove the attribute after you hover:

 function a() { document.body.innerHTML += 'uu'; let c = document.getElementById("btnTest"); c.removeAttribute('onmouseover'); }
 <button id="btnTest" onMouseOver="a()">hello world</button>

This will only allow the function to run once per page load, so if you need it to work after removing and replacing the mouse again, we will need to adjust it.

It should even if you stop hovering and come back and still not refresh the page it will work

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