onfocus 事件

定义和用法

onfocus 事件在对象获得焦点时发生。

语法

  1. onfocus="SomeJavaScriptCode"
参数 描述
SomeJavaScriptCode 必需。规定该事件发生时执行的 JavaScript。

支持该事件的 HTML 标签:

  1. <a>, <acronym>, <address>, <area>, <b>, <bdo>, <big>, <blockquote>, <button>,
  2. <caption>, <cite>, <dd>, <del>, <dfn>, <div>, <dl>, <dt>, <em>, <fieldset>,
  3. <form>, <frame>, <frameset>, <h1> to <h6>, <hr>, <i>, <iframe>, <img>, <input>,
  4. <ins>, <kbd>, <label>, <legend>, <li>, <object>, <ol>, <p>, <pre>, <q>,
  5. <samp>, <select>, <small>, <span>, <strong>, <sub>, <sup>, <table>, <tbody>,
  6. <td>, <textarea>, <tfoot>, <th>, <thead>, <tr>, <tt>, <ul>, <var>

支持该事件的 JavaScript 对象:

  1. button, checkbox, fileUpload, layer, frame, password, radio, reset, select, submit,
  2. text, textarea, window

实例

在本例中,当输入框获得焦点时,其背景颜色将改变:

  1. <html>
  2. <head>
  3. <script type="text/javascript">
  4. function setStyle(x)
  5. {
  6. document.getElementById(x).style.background="yellow"
  7. }
  8. </script>
  9. </head>
  10.  
  11. <body>
  12.  
  13. First name: <input type="text"
  14. onfocus="setStyle(this.id)" id="fname" />
  15. <br />
  16. Last name: <input type="text"
  17. onfocus="setStyle(this.id)" id="lname" />
  18.  
  19. </body>
  20. </html>

输出:

First name:

Last name: