JS Prompt能自定義按鈕文本嗎

js
小樊
81
2024-10-12 21:35:26
欄目: 編程語言

JavaScript的prompt()函數(shù)本身不支持自定義按鈕文本。prompt()函數(shù)會(huì)顯示一個(gè)帶有指定提示信息和默認(rèn)輸入框的對(duì)話框,用戶可以在其中輸入信息。但是,prompt()函數(shù)并沒有提供直接的方式來修改按鈕的文本。

如果你需要自定義按鈕文本,你可能需要使用其他方法來實(shí)現(xiàn)這個(gè)功能。例如,你可以創(chuàng)建一個(gè)自定義的模態(tài)對(duì)話框(modal dialog)來代替prompt()函數(shù)。在這個(gè)自定義對(duì)話框中,你可以完全控制按鈕的文本和其他樣式。

下面是一個(gè)簡(jiǎn)單的示例,展示了如何使用HTML、CSS和JavaScript創(chuàng)建一個(gè)自定義的模態(tài)對(duì)話框:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Custom Prompt</title>
    <style>
        /* 模態(tài)對(duì)話框樣式 */
        .modal {
            display: none; /* 默認(rèn)隱藏 */
            position: fixed; /* 固定位置 */
            z-index: 1; /* 確保在最上層 */
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0,0,0,0.4); /* 背景半透明 */
        }

        .modal-content {
            background-color: #fefefe;
            margin: 15% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
        }

        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }

        .close:hover,
        .close:focus {
            color: black;
            text-decoration: none;
            cursor: pointer;
        }
    </style>
</head>
<body>

<!-- 模態(tài)對(duì)話框 -->
<div id="myModal" class="modal">
    <div class="modal-content">
        <span class="close">&times;</span>
        <p>請(qǐng)輸入你的信息:</p>
        <input type="text" id="customInput">
        <button id="customButton">確定</button>
    </div>
</div>

<script>
    // 獲取模態(tài)對(duì)話框和按鈕元素
    var modal = document.getElementById("myModal");
    var btn = document.getElementById("customButton");
    var span = document.getElementsByClassName("close")[0];

    // 點(diǎn)擊按鈕打開模態(tài)對(duì)話框
    btn.onclick = function() {
        modal.style.display = "block";
    }

    // 點(diǎn)擊關(guān)閉按鈕關(guān)閉模態(tài)對(duì)話框
    span.onclick = function() {
        modal.style.display = "none";
    }

    // 點(diǎn)擊模態(tài)對(duì)話框外部區(qū)域關(guān)閉模態(tài)對(duì)話框
    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }
</script>

</body>
</html>

在這個(gè)示例中,我們創(chuàng)建了一個(gè)自定義的模態(tài)對(duì)話框,其中包含一個(gè)輸入框和一個(gè)按鈕。你可以通過修改CSS樣式來自定義按鈕和其他元素的文本和樣式。點(diǎn)擊按鈕時(shí),模態(tài)對(duì)話框會(huì)顯示出來,你可以輸入信息并點(diǎn)擊確定按鈕。點(diǎn)擊關(guān)閉按鈕或模態(tài)對(duì)話框外部區(qū)域時(shí),模態(tài)對(duì)話框會(huì)關(guān)閉。

0