onfocus-tapahtuma
Määritelmä ja käyttö
onfocus-tapahtuma tapahtuu, kun elementti saa keskittyvyyden.
onfocus-tapahtumaa käytetään yleensä yhdessä <input>-, <select>- ja <a>-elementtien kanssa.
Vinkki: onfocus-tapahtuma muistuttaa onblur-tapahtumapäinvastoin.
Vinkki: onfocus-tapahtuma muistuttaa onfocusin-tapahtumaPääasiallinen ero on, että onfocus-tapahtuma ei suoda. Siksi, jos haluat määrittää, onko elementti tai sen lapsielementti saanut keskittyvyyden, voit käyttää onfocusin tapahtumaa. Mutta voit käyttää onfocus-tapahtumaa addEventListener() metodi。 useCapture parametrien avulla tämä voidaan tehdä.
Esimerkki
Esimerkki 1
Suorita JavaScript, kun syöteala saavuttaa keskittyvyyden:
<input type="text" onfocus="myFunction()">
Sivun alaosassa on lisää TIY-esimerkkejä.
Syntaksi
HTML:ssä:
<elementti onfocus="myScript">
JavaScriptissa:
objekti.onfocus = function(){myScript};
JavaScriptissa käytetään addEventListener() metodia:
objekti.addEventListener("focus", myScript);
Huomautus:Internet Explorer 8 tai aikaisemmat versiot eivät tue addEventListener() metodi。
Technical details
Bubble: | Not supported |
---|---|
Cancelable: | Not supported |
Event type: | FocusEvent |
Supported HTML tags: | All HTML elements except: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style> and <title> |
DOM version: | Level 2 Events |
Browser support
Event | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
onfocus | Supported | Supported | Supported | Supported | Supported |
More examples
Example 2
Use "onfocus" and "onblur" events together:
<input type="text" onfocus="focusFunction()" onblur="blurFunction()">
Example 3
Clear the focused input field:
/* When the input field receives focus, replace its current value with an empty string */ <input type="text" onfocus="this.value=''" value="Blabla">
Example 4
Event delegation: Set the useCapture parameter of addEventListener() to true:
<form id="myForm"> <input type="text" id="myInput"> </form> <script> var x = document.getElementById("myForm"); x.addEventListener("focus", myFocusFunction, true); x.addEventListener("blur", myBlurFunction, true); function myFocusFunction() { document.getElementById("myInput").style.backgroundColor = "yellow"; } function myBlurFunction() { document.getElementById("myInput").style.backgroundColor = ""; } </script>
Example 5
Event delegation: Using the focusin event (not supported by Firefox):
<form id="myForm"> <input type="text" id="myInput"> </form> <script> var x = document.getElementById("myForm"); x.addEventListener("focusin", myFocusFunction); x.addEventListener("focusout", myBlurFunction); function myFocusFunction() { document.getElementById("myInput").style.backgroundColor = "yellow"; } function myBlurFunction() { document.getElementById("myInput").style.backgroundColor = ""; } </script>