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


HTML DOM focus()用法及代碼示例


DOM focus()方法用於為元素賦予焦點,並借助blur()方法刪除焦點。我們可以將焦點放在任何元素上,並通過執行一些操作來啟用它。例如,我們可以通過單擊按鈕將焦點放在某些文本上。

用法:

Object.focus()

示例1:


<!DOCTYPE html>  
<html>  
    <head>  
        <title>DOM focus() Method</title> 
              <style> 
                  input[type=text]:focus { 
                   background-color:red; 
                  } 
               </style>  
    </head>  
      
    <body>  
        <center>  
            <input type="text" id="gfg" value="GeeksForGeeks"> 
            <h2>DOM focus() Method </h2>      
            <button type = "button" onclick = "geek()">  
               Submit 
            </button>  
              
            <script>  
               function geek() {  
               document.getElementById("gfg").focus();  
               }  
            </script> 
   
        </center>  
    </body>  
</html>                     

輸出:
在應用焦點之前:

應用焦點後:

示例2:

<!DOCTYPE html>  
<html>  
    <head>  
        <title>DOM focus() Method</title>  
              <style> 
                  a:focus { 
                   background-color:magenta; 
                 } 
              </style>  
    </head>  
    <body>  
        <center>  
            <h1 style="color:green;">  
                GeeksForGeeks  
            </h1>  
              
            <h2>DOM focus() Method</h2>  
              
            <a href="www.geeksforgeeks.com" 
                id = "geek">geeksforgeeks</a>  
            <br>  
            <button type = "button" onclick = "geeks()">  
               Submit  
            </button>  
              
            <script>  
                function geeks() {  
                    document.getElementById("geek").focus(); 
  
                }  
            </script>  
        </center>  
    </body> 

輸出:
在應用焦點之前:

應用焦點後:

支持的瀏覽器:下麵列出了DOM focus()方法支持的瀏覽器:

  • 穀歌瀏覽器15.0
  • Internet Explorer 11.0
  • Firefox 15.0
  • Opera 15.0
  • Safari 6.0


相關用法


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