表單欄位加上即時提示,是提升可用性很划算的小細節。做法是在頁面放一個絕對定位的提示層,於欄位 onfocus 時依欄位座標定位並顯示文字,onblur 時收起。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>html 文字框提示效果</title>
<style type="text/css">
* { margin: 0px; padding: 0px; font-size: 12px; }
input {
width: 100px;
height: 20px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<script language="javascript">
function tips(id, str) {
var l = document.getElementById(id).offsetLeft + 120;
var t = document.getElementById(id).offsetTop;
document.getElementById("tips").innerHTML = "提示:" + str;
document.getElementById("tips").style.left = l + "px";
document.getElementById("tips").style.top = t + "px";
document.getElementById("tips").style.display = "";
}
function outtips() {
document.getElementById("tips").style.display = 'none';
}
</script>
<div id="tips" style="position:absolute; border:1px solid #ccc; padding:0px 3px;
color:#f00; display:none; height:20px; line-height:20px; background:#fcfcfc"></div>
<br />
姓名:<input type="text" id="username"
onfocus="tips('username','姓名長度最多 16 個字符')" onblur="outtips()" />
<br />
密碼:<input type="password" id="password"
onfocus="tips('password','密碼長度必須在 3-18 位之間')" onblur="outtips()" />
</body>
</html>
幾點可調整的地方:提示層的 offsetLeft + 120 是硬寫的偏移量,實務上建議改用欄位寬度 offsetWidth 加固定間距,換版面時才不會跑位;另外若要支援無障礙,可以搭配 aria-describedby 讓螢幕閱讀器也能讀到提示內容,效果比純視覺提示更完整。