📜  在 HTML 中加载页面时如何聚焦元素?

📅  最后修改于: 2022-05-13 01:56:15.464000             🧑  作者: Mango

在 HTML 中加载页面时如何聚焦元素?

超文本标记语言(HTML) 是定义结构的网页的基本构建块。浏览器使用这种标记语言来处理文本、图像和其他内容等数据,以便它们可以以所需的格式显示。超文本是指连接网页的链接,标记定义了标签内的文本文档。

在 HTML 中加载页面时如何聚焦元素?

我们希望每当我们加载页面时元素都应该成为焦点。我们可以通过两种方式做到这一点:

  • 使用元素的autofocus 属性
  • 使用窗口:加载事件

让我们通过示例来探索这两种方式。

1. 使用自动对焦属性自动对焦属性是一个布尔属性,即它只能是真或假。当这个属性出现在一个元素中时,它指定它所在的元素应该在页面加载时自动获得焦点。

自动对焦属性只能在下面提到的元素中使用——

  • <输入>
  • <按钮>
  • <文本区域>
  • <选择>

句法:

示例:在此示例中,每当页面加载时,输入元素都会获得焦点,我们可以看到它作为输入的背景颜色更改为#8ecae6。

HTML


  

    Using autofocus attribute
    

  

    
        

GeeksforGeeks

                
  


CSS
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
  
div {
    margin: auto;
    margin-top: 10px;
    height: 100px;
    width: 300px;
    background-color: green;
    text-align: center;
    font-size: 24px;
    font-family: Arial, Helvetica, sans-serif;
}
  
p {
    padding-top: 15px;
    color: whitesmoke;
}
  
input {
    margin-top: 15px;
    width: 75%;
    color: black;
    font-weight: bolder;
}
  
input:focus {
    background-color: #8ecae6;
}


HTML


  

    Using load event
    

  

    
        

GeeksforGeeks

             
       


CSS
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
  
div {
    margin: auto;
    margin-top: 10px;
    height: 100px;
    width: 300px;
    background-color: green;
    text-align: center;
    font-size: 24px;
    font-family: Arial, Helvetica, sans-serif;
}
  
p {
    padding-top: 15px;
    color: whitesmoke;
}
  
input {
    margin-top: 15px;
    width: 75%;
    color: black;
    font-weight: bolder;
}
  
input:focus {
    background-color: #8ecae6;
}


Javascript
let inputElem = document.querySelector("input");
window.addEventListener('load', function(e) {
    inputElem.focus();
})


输出:

2. 使用窗口: load 事件:窗口对象的加载事件在整个页面加载完成时触发,包括样式表和图像。现在,当页面加载完毕后,我们可以使用HTMLElement.focus()方法为我们的元素提供焦点(如果可以获得焦点)。默认情况下,焦点元素是接收键盘和类似事件的元素。

句法:

HTMLElement.focus();

focus() 方法可以有一个可选参数,该参数是一个提供选项来控制聚焦过程的各个方面的对象。

例子:

HTML



  

    Using load event
    

  

    
        

GeeksforGeeks

             
       

CSS

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
  
div {
    margin: auto;
    margin-top: 10px;
    height: 100px;
    width: 300px;
    background-color: green;
    text-align: center;
    font-size: 24px;
    font-family: Arial, Helvetica, sans-serif;
}
  
p {
    padding-top: 15px;
    color: whitesmoke;
}
  
input {
    margin-top: 15px;
    width: 75%;
    color: black;
    font-weight: bolder;
}
  
input:focus {
    background-color: #8ecae6;
}

Javascript

let inputElem = document.querySelector("input");
window.addEventListener('load', function(e) {
    inputElem.focus();
})

输出:

支持的浏览器: