Skip to content

[JavaScript] 使用 alert()、confirm()、prompt() 以及自制部件等不同方法彈出視窗畫面

在設計網頁與使用者的互動時,總免不了要製作跳出提醒、甚至是跟使用者進行確認、讓使用者輸入資訊等等不同的彈出視窗(popup window)。

本篇文章紀錄以下四種簡單的視窗製作方法:

  • window.alert()
  • window.confirm()
  • window.prompt()
  • 自製隱藏、顯示的視窗部件

(註:以上的 window 可以省略)

備註:不同瀏覽器的樣式可能會有不同


alert() 範例

alert() 是非常單純的彈出視窗,經常用於顯示一些基本訊息。

<html>
    <body>
        <button onclick="alertEvent()">Alert</button>
    </body>

    <script>
        function alertEvent() {
            alert("This is the alert message!");
        }
    </script>
</html>


Output:


confirm() 範例

alert() 不同,confirm() 是可以根據使用者的接受與否來做出不同的回應。

<html>
    <body>
        <button onclick="confirmEvent()">Confirm</button>
    </body>

    <script>
        function confirmEvent() {
            if (confirm("Are you sure?") == true) {
                alert("YES!");
            }
            else {
                alert("No!");
            }
        }
    </script>
</html>


Output:


prompt() 範例

prompt() 最常用於需要訪客輸入的情況了,在訪客輸入並按下確定後,會返回輸入值,若是取消會返回空值 null。不過在比較講究設計的網站中多半不會拿 prompt() 來當作正式的輸入元件使用。

畢竟……有些簡陋。

<html>
    <body>
        <button onclick="promptEvent()">Prompt</button>
    </body>

    <script>
        function promptEvent() {
            var name = prompt("Can I have your name, please?");
            if (name == null || name == "") {
                alert("Sorry, I don't know how to call you!");
            }
            else {
                var message = "Hello! Nice to meet you, " + name + "!";
                alert(message);
            }
        }
    </script>
</html>


Output:


自製視窗部件

<html>
    <style>
#window-container{
    display: none;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
}
       
#window-pop{
    background: white;
    width:30%;
    z-index: 1;
    margin: 12% auto;
    overflow: auto;
    border-radius: 20px;
}
        
.window-content {
    width: auto;
    height: 200px;
    line-height: 200px
    overflow: auto;
    text-align: center;
}

span {
    display: inline-block;
    vertical-align: middle;
    line-height: normal;
}

    </style>


    <body>
        <div id="window-container">
            <div id="window-pop">
                <div class="window-content">
                    <span>You can display content here!</span>
                </div>
            </div>
        </div>


        <button onclick="customizeWindowEvent()">Click Me</button>
    </body>

    <script>
        function customizeWindowEvent() {
            var popup_window = document.getElementById("window-container");

            popup_window.style.display = "block";

            window.onclick = function close(e) {
                if (e.target == popup_window) {
                    popup_window.style.display = "none";
                }
            }
        }
    </script>
</html>


Output:

You can display content here!

點擊彈出視窗外的範圍即可關閉。


References


Read More

Leave a Reply