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


HTML DOM Button autofocus属性用法及代码示例

HTML DOM Button autofocus 属性与 <button> 元素的 autofocus 属性相关联。 button autofocus 属性用于指定 HTML 文档上的按钮在页面加载时是否应该获得焦点。

用法

以下是语法 -

设置按钮自动对焦属性 -

buttonObject.autofocus = true|false

在这里, true|false 指定给定的输入按钮是否应该在页面加载时获得焦点。

  • True − 输入按钮获得焦点
  • False- 输入按钮没有获得焦点。

示例

让我们看一个 HTML DOM 按钮自动对焦属性的例子 -

<!DOCTYPE html>
<html>
<body>
<button type="button" id="MyButton" autofocus>BUTTON</button>
<p>Click the below button to know if the input button above automatically gets the focus on page load or not</p>
<button onclick="buttonFocus()">CLICK IT</button>
<p id="Sample"></p>
<script>
   function buttonFocus() {
      var x = document.getElementById("MyButton").autofocus;
      if(x==true)
         document.getElementById("Sample").innerHTML="The input button does get focus on page load";
      else
         document.getElementById("Sample").innerHTML="The input button does not get focus on
      page load";
   }
</script>
</body>
</html>

输出

这将产生以下输出 -

单击“单击它”按钮 -

在上面的例子中 -

我们有一个按钮,id “MyButton” 并启用了自动对焦属性 -

<button type="button" id="MyButton" autofocus>BUTTON</button>

然后我们有一个 CLICK IT 按钮来执行 buttonFocus() 函数 -

<button onclick="buttonFocus()">CLICK IT</button>

buttonFocus() 函数使用 getElementById() 方法获取按钮元素并获取其自动对焦值,该值是布尔值并将其分配给变量 x。使用条件语句,我们检查自动对焦值是否为真和假,并相应地在与 id “Sample” 关联的 <p> 元素中显示合适的文本。

function buttonFocus() {
   var x = document.getElementById("MyButton").autofocus;
   if(x==true)
      document.getElementById("Sample").innerHTML="The input button does get focus on page load";
   else
      document.getElementById("Sample").innerHTML="The input button does not get focus on page load";
}

相关用法


注:本文由纯净天空筛选整理自AmitDiwan大神的英文原创作品 HTML DOM Button autofocus Property。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。