DIV CSS 佈局教程網

JavaScript 控制按鈕啟用與停用(disabled)的方法
編輯:關於JavaScript     

控制一個按鈕能不能按,靠的是 disabled 屬性。設為 true 就變灰不可點,設為 false 恢復可用,就這麼單純。

<!DOCTYPE html>
<html>
<body>
<form>
Buttons:
<input type="button" id="firstbtn" value="OK">
<input type="button" id="secondbtn" value="OK">
</form>

<p>Click the button below to disable the first button above.</p>
<button onclick="disableElement()">Disable button</button>

<script>
function disableElement() {
    document.getElementById("firstbtn").disabled = true;
}
</script>
</body>
</html>

常見的三種應用情境

防止重複送出。表單送出後立刻鎖住按鈕,避免使用者連點造成重複訂單:

document.querySelector("form").addEventListener("submit", function () {
    this.querySelector('button[type="submit"]').disabled = true;
    // 表單會照常送出,disabled 只影響後續點擊
});

依表單狀態切換。例如條款核取方塊沒勾之前,下一步不能按:

var agree = document.getElementById("agree");
var next = document.getElementById("nextbtn");

function sync() {
    next.disabled = !agree.checked;
}
agree.addEventListener("change", sync);
sync();  // 初始狀態也要套用一次

等待非同步作業完成。上傳或查詢進行中先鎖住,完成後再開放。

幾個容易忽略的細節

disabled 的元素不會送出。這是最常踩的坑。被設為 disabled 的表單欄位,其 name/value 不會出現在送出的資料裡。如果你只是「不想讓使用者改」,但值必須送出,請改用 readOnly = true(注意 readonly 對 <select> 和核取方塊無效)。

disabled 元素不觸發滑鼠事件。在 .disabled = true 的元素上掛 click 或 mouseover 都不會有反應。想做「點了但提示為什麼不能按」的效果,得把提示包在外層容器上,而不是掛在按鈕本身。

樣式記得一起處理。瀏覽器預設會把 disabled 按鈕變灰,但如果你自訂了 background-color,那個灰階效果會被蓋掉,看起來就像還能按。請補上 button:disabled { opacity: .5; cursor: not-allowed; }。

別只靠前端鎖。disabled 只是使用者介面的提示,用 devtools 一行就能改回來。伺服器端一定要再驗一次權限與資料合法性,這是基本原則。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved