当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。