onblur 事件會在元素失去焦點時發生,常用於輸入框離開時的驗證、格式化或自動轉換。
onblur="SomeJavaScriptCode"其中 SomeJavaScriptCode 代表事件發生時要執行的 JavaScript 程式碼。
許多可互動元素都支援 blur 事件,例如 input、textarea、select、button、a、form 等。在表單驗證中,onblur 特別常用,因為它能在使用者離開欄位時立即檢查內容。
<html>
<head>
<script type="text/javascript">
function upperCase() {
var x = document.getElementById("fname").value;
document.getElementById("fname").value = x.toUpperCase();
}
</script>
</head>
<body>
輸入您的姓名:
<input type="text" id="fname" onblur="upperCase()" />
</body>
</html>當使用者在文字輸入框輸入內容後,將焦點移到其他地方,輸入內容就會被轉成英文大寫。
onblur 很適合用於即時格式整理、必填檢查、去除空白、提示錯誤等互動。與表單提交時才驗證相比,它能更早給使用者回饋。