JavaScript 方法 focus() 如何工作?


focus()

Javascript focus() 方法幫助突出一個 HTML 表單元素。它將該元素設定為當前文件中的活動元素。在當前文件中,focus 只能應用於一個元素。焦點可以應用於文字或按鈕等內容。 

語法

element.focus(options);

示例

在以下示例中,最初文字“Tutorialspoint”位於一個錨標記“a”中,該標記有一個名為“focus”的 id。稍後,聲明瞭一個函式,在其中使用 DOM 方法呼叫該 id,並在其上應用 focus() 方法,將文字“Tutorialspoint”的顏色更改為紅色。此處使用一個按鈕進行單擊事件。

即時演示

<html>
<head>
<style>
   a:focus, a:active {
      color: red;
   }
</style>
</head>
<body>
<a href="https://tutorialspoint.tw/" id="focus">Tutorialspoint</a>
<input type="button" value="getfocus" onclick="getfo()">
<script>
   function getfo() {
      document.getElementById("focus").focus();
   }
</script>
</body>
</html>

執行上述程式碼後,將在螢幕上顯示以下影像。



一旦我們單擊獲取焦點按鈕,我們將獲得以下輸出。

輸出

更新時間:2019-7-30

1000+ 瀏覽

開啟你的職業生涯

完成課程以獲得認證

開始
廣告