JavaScript:點擊任一按鈕使其他按鈕無法點擊

2019/10/26 2,626 0 網站技術 , HTML , JavaScript

這次要教學的是寫一個短短的 JavaScript 原始碼就可以做到「點擊任一按鈕使其他按鈕無法點擊」,同場加映 3 秒後恢復原狀!會使用到 getElementById 取得按鈕 ID,接著運用 onclick (點擊)事件改變另外兩顆按鈕,為他們加上屬性 disabled 與其值 disabled,這樣就停用這兩顆按鈕啦!三顆按鈕都做好後最後就是加映場,一樣也是做三個按鈕,不過這次用的是 addEventListener (添加事件監聽)的 click (點擊)事件,這是用來監聽點擊事件用的原始碼,接著用 setTimeout 這個方法設定 3 秒(3000,1000 = 一秒)後執行指定原始碼,指定原始碼當然就是寫把另外兩顆按鈕的 HTML 屬性 disabled 移除,這樣就達到恢復原狀。這是一個相當簡易的寫法,也很容易懂,給大家參考啦!


▲ 示範原始碼與執行結果局部截圖。

▲ CodePen 示範。

⌨️ 完整原始碼提供:

<!DOCTYPE html>
<html lang="zh-tw">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>點擊任一按鈕使其他按鈕無法點擊</title>
    <script>
        window.onload = function () {

            // 點按鈕1將按鈕2與3停用
            document.getElementById("button1").onclick = function () {
                document.getElementById("button2").setAttribute("disabled", "disabled");
                document.getElementById("button3").setAttribute("disabled", "disabled");
            };

            // 點按鈕2將按鈕1與3停用
            document.getElementById("button2").onclick = function () {
                document.getElementById("button1").setAttribute("disabled", "disabled");
                document.getElementById("button3").setAttribute("disabled", "disabled");
            };

            // 點按鈕3將按鈕1與2停用
            document.getElementById("button3").onclick = function () {
                document.getElementById("button1").setAttribute("disabled", "disabled");
                document.getElementById("button2").setAttribute("disabled", "disabled");
            };

            // 同場加映:3 秒後恢復原狀
            document.getElementById("button1").addEventListener("click", function () {
                setTimeout(
                    "document.getElementById('button2').removeAttribute('disabled');document.getElementById('button3').removeAttribute('disabled');",
                    3000)
            });

            document.getElementById("button2").addEventListener("click", function () {
                setTimeout(
                    "document.getElementById('button1').removeAttribute('disabled');document.getElementById('button3').removeAttribute('disabled');",
                    3000)
            });

            document.getElementById("button3").addEventListener("click", function () {
                setTimeout(
                    "document.getElementById('button1').removeAttribute('disabled');document.getElementById('button2').removeAttribute('disabled');",
                    3000)
            });

        }
    </script>
</head>

<body>
    <button id="button1">按鈕1</button>
    <button id="button2">按鈕2</button>
    <button id="button3">按鈕3</button>
</body>

</html>
贊助廣告 ‧ Sponsor advertisements

留言區 / Comments

萌芽論壇