共計 922 個字符,預計需要花費 3 分鐘才能閱讀完成。
在 JavaScript 中,可以使用 disabled
屬性來啟用或禁用按鈕。當 disabled
屬性的值為 true
時,按鈕將被禁用,用戶將無法點擊它;當 disabled
屬性的值為 false
時,按鈕將被啟用,用戶可以點擊它。
以下是一些使用 JavaScript 啟用 / 禁用按鈕的示例:
- 使用
getElementById
方法獲取按鈕的引用,然后通過設置disabled
屬性來禁用按鈕:
var button = document.getElementById('myButton'); // 獲取按鈕的引用
button.disabled = true; // 禁用按鈕
- 使用
querySelector
方法選擇按鈕,并設置disabled
屬性來禁用按鈕:
var button = document.querySelector('button'); // 選擇按鈕
button.disabled = true; // 禁用按鈕
- 通過添加 / 移除
disabled
屬性來啟用 / 禁用按鈕:
var button = document.getElementById('myButton'); // 獲取按鈕的引用
button.setAttribute('disabled', 'disabled'); // 禁用按鈕
// 或者 button.disabled = true;
// 啟用按鈕
button.removeAttribute('disabled');
// 或者 button.disabled = false;
- 在 HTML 中,可以使用
onclick
屬性來調用 JavaScript 函數,并在函數中啟用 / 禁用按鈕:
function toggleButton() {var button = document.getElementById('myButton');
button.disabled = !button.disabled; // 切換按鈕的狀態
}
上述示例中的 getElementById
、querySelector
、setAttribute
和 removeAttribute
是 DOM(文檔對象模型)的一部分,它們可以用于獲取元素的引用、設置屬性和移除屬性。通過操作按鈕的 disabled
屬性,可以方便地啟用或禁用按鈕。
丸趣 TV 網 – 提供最優質的資源集合!
正文完