如何去除點選按鈕後按鈕周圍的焦點?
在構建 Web 應用程式時,您可能會注意到點選按鈕時往往會在按鈕周圍留出輪廓或“聚焦環”。這有助於輔助功能,但有時對於特定設計來說是不需要的。在本文中,我們將探討幾種在點選時去除按鈕聚焦環的方法,同時不犧牲鍵盤使用者的輔助功能。
點選時去除按鈕周圍焦點的途徑
使用 JavaScript 的 addEventListener 方法
為了確保僅在滑鼠點選時隱藏焦點環,但在鍵盤導航時仍然可見,我們可以使用 JavaScript 的 addeventlistener() 方法來檢測點選並有選擇地去除輪廓。
示例程式碼
<!DOCTYPE html> <html lang="en"> <head> <title>Remove Focus on Button Click</title> <style> button { padding: 10px 20px; border: 2px solid #007bff; border-radius: 5px; background-color: #007bff; color: white; } button:focus { outline: 2px solid #333; } </style> </head> <body> <button onclick="removeFocusOnClick(this)"> Click Me </button> <script> function removeFocusOnClick(button) { button.style.outline = 'none'; button.addEventListener('blur', function() { button.style.outline = ''; }); } </script> </body> </html>
輸出
使用 CSS 偽類
在該途徑中,我們使用 CSS 僅在使用鍵盤時應用焦距樣式,確保焦點環在滑鼠點選時隱藏,但在鍵盤使用者使用時依然可以訪問。這可以透過 :focus-visible 偽類實現。
示例程式碼
<!DOCTYPE html> <html lang="en"> <head> <title>Remove Focus on Button Click</title> <style> button { padding: 10px 20px; border: 2px solid #007bff; border-radius: 5px; background-color: #007bff; color: white; } button:focus-visible { outline: 2px solid #333; } </style> </head> <body> <button>Click Me</button> </body> </html>
輸出
廣告