HTML - DOM blur() 方法



HTML DOM 的 blur() 方法用於動態地從 HTML DOM 中的元素中移除鍵盤焦點。從元素中移除焦點是指將鍵盤焦點從特定元素(例如輸入欄位或按鈕)移開。

DOM 提供了另一種名為 focus() 的方法,您可以使用它來在 HTML DOM 中的任何元素上設定焦點。

語法

以下是 HTML DOM blur() 方法的語法:

Object.blur();

引數

此方法不接受任何引數。

返回值

此方法不返回值。

示例 1:從輸入欄位中移除焦點

以下是 HTML DOM blur() 方法的基本示例,用於在單擊按鈕時從輸入欄位中移除焦點:

<!DOCTYPE html>
<html lang="en">
<head> 
<title>HTML DOM blur()</title>
</head>
<body>
<p>Click the button to blur the input field.</p>  
<input type="text" id="myInput" placeholder="Type something...">
<button onclick="blurInput()">Blur Input</button>
<script>
   function blurInput() {
      const input = document.getElementById('myInput');
      input.blur();
   }
</script>
</body>
</html>

示例 2:在錨點 (<a>) 元素上使用 blur() 方法

以下是 HTML DOM blur() 方法的另一個示例。我們使用此方法從錨點 (<a>) 元素中移除焦點:

<!DOCTYPE html>
<html lang="en">
<head> 
<title>HTML DOM blur()</title>
</head>
<body> 
<p>Click the button to blur the anchor element.</p>
<a id="myAnchor" href="https://www.example.com">Example Anchor</a>
<button onclick="blurAnchor()">Blur Anchor Element</button>
<script>
   function blurAnchor() {
      const myAnchor = document.getElementById('myAnchor');
      myAnchor.blur();
      alert('Anchor element blurred!');
   }
</script>
</body>
</html>  

示例 3:單擊任何位置時模糊

下面的示例演示了 blur() 方法如何與事件監聽器一起使用。當您單擊輸入欄位並在欄位外部單擊時,將彈出一個帶有“輸入欄位已模糊”訊息的彈出視窗:

<!DOCTYPE html>
<html lang="en">
<head> 
<title>HTML DOM blur()</title>
</head>
<body>
    <p>Click anywhere outside the input field to blur it.</p>
    <input type="text" id="myInput" value="Edit Me!">

    <script>
        const myInput =document.getElementById('myInput');
        myInput.addEventListener('blur', () => {
            alert('Input field blurred!'); 
        });
    </script>
</body>
</html>     

支援的瀏覽器

方法 Chrome Edge Firefox Safari Opera
blur()
html_dom_element_reference.htm
廣告