如何在螢幕中央顯示 JavaScript 警報框?


要在中間顯示 JavaScript 警報框,你必須使用自定義警報框。在此基礎上,為其設定樣式,並將其置於中間。使用 CSS 中的 “top” 和 “left” 特性來實現此目的。將它們設定為 50%,但由於你可以在下方看到一個按鈕,將該特性設定為 40%,以使其與按鈕對齊

示例

動態演示

<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         function functionAlert(msg, myYes) {
            var confirmBox = $("#confirm");
            confirmBox.find(".message").text(msg);
            confirmBox.find(".yes").unbind().click(function() {
               confirmBox.hide();
            });
            confirmBox.find(".yes").click(myYes);
            confirmBox.show();
         }
      </script>
      <style>
         #confirm {
            display: none;
            background-color: #F3F5F6;
            color: #000000;
            border: 1px solid #aaa;
            position: fixed;
            width: 300px;
            height: 100px;
            left: 40%;
            top: 40%;
            box-sizing: border-box;
            text-align: center;
         }
         #confirm button {
            background-color: #FFFFFF;
            display: inline-block;
            border-radius: 12px;
            border: 4px solid #aaa;
            padding: 5px;
            text-align: center;
            width: 60px;
            cursor: pointer;
         }
         #confirm .message {
            text-align: left;
         }
      </style>
   </head>
   <body>
      <div id="confirm">
         <div class="message">This is a warning message.</div><br>
         <button class="yes">OK</button>
      </div>
      <input type="button" value="Click Me" onclick="functionAlert();" />
   </body>
</html>

更新於: 2019-09-25

1000+ 次瀏覽

開啟你的 事業

完成課程以獲得認證

開始
廣告
© . All rights reserved.