當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


HTML onfocus事件用法及代碼示例


當元素獲得焦點時,將發生HTML DOM onfocus事件。 onfocus事件通常與<input>,<select>和<a>一起使用。 onfocus事件與onblur事件相反。

HTML DOM onfocus事件支持除以下所有HTML標記:

  • <base>
  • <bdo>
  • <br>
  • <head>
  • <html>
  • <iframe>
  • <meta>
  • <param>
  • <script>
  • <style>
  • <title>

用法:


  • 在HTML中:
    <element onfocus="myScript">
  • 在JavaScript中:
    object.onfocus = function(){myScript};
  • 在JavaScript中,使用addEventListener()方法:
    object.addEventListener("focus", myScript);

注意:onfocus事件與onfocusin事件不同,因為onfocus事件不會冒泡。

範例1:

<!DOCTYPE html> 
<html> 
  
<head> 
    <title> 
      HTML DOM onfocus Event 
  </title> 
</head> 
  
<body> 
    <center> 
        <h1 style="color:green"> 
          GeeksforGeeks 
      </h1> 
        <h2> 
          HTML DOM onfocus Event 
      </h2> 
        <br> Name:
        <input type="text" 
               onfocus="geekfun(this)"> 
        <script> 
            function geekfun(gfg) { 
                gfg.style.background = "green"; 
            } 
        </script> 
  </center> 
</body> 
  
</html>

輸出:

範例2:

<!DOCTYPE html> 
<html> 
  
<head> 
    <title> 
      HTML DOM onfocus Event 
  </title> 
</head> 
  
<body> 
    <center> 
        <h1 style="color:green"> 
          GeeksforGeeks 
      </h1> 
        <h2>HTML DOM onfocus Event</h2> 
        <br> Name:
        <input type="text" id="fname"> 
  
        <script> 
            document.getElementById( 
              "fname").onfocus = function() { 
                geekfun() 
            }; 
  
            function geekfun() { 
                document.getElementById( 
                  "fname").style.backgroundColor = 
                  "green"; 
            } 
        </script> 
    </center> 
</body> 
  
</html>

輸出

範例3:

<!DOCTYPE html> 
<html> 
  
<head> 
    <title> 
      HTML DOM onfocus Event 
  </title> 
</head> 
  
<body> 
    <center> 
        <h1 style="color:green"> 
          GeeksforGeeks 
      </h1> 
        <h2>HTML DOM onfocus Event</h2> 
        <br> Name:
        <input type="text" id="fname"> 
  
        <script> 
            document.getElementById( 
              "fname").addEventListener( 
              "focus", Geeksfun); 
  
            function Geeksfun() { 
                document.getElementById( 
                  "fname").style.backgroundColor = "green"; 
            } 
        </script> 
    </center> 
</body> 
  
</html>

輸出:

支持的瀏覽器:下麵列出了HTML DOM onfocus事件支持的瀏覽器:

  • 穀歌瀏覽器
  • IE瀏覽器
  • Firefox
  • 蘋果Safari
  • Opera


相關用法


注:本文由純淨天空篩選整理自Vijay Sirra大神的英文原創作品 HTML | DOM onfocus Event。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。