如何更改警告框的样式?

161

我需要更改 警告框 中 "确定" 按钮的样式。

<head>
    <script type="text/javascript">
        function show_alert() {
            alert("Hello! I am an alert box!");
        }
    </script>
</head>
<body>
    <input type="button" onclick="show_alert()" value="Show alert box" />
</body>


7
请不要使用警告框(alert boxes),有更好的选项。仅将其用于调试(debugging)。 - Ed Heal
29
笑死,EdHeal,请不要用那些来进行调试!哈哈,有更好的选择哈哈。 - EricG
1
我从一个无聊的东西开始,xD http://codepen.io/anon/pen/tFhKu - EricG
10
因为接受jQuery作为“答案”,被点踩了。正确的答案是主张在CSS规范中尝试标准化某个东西。 - John
你可以使用纯JS创建一个警告框。https://dev59.com/AWox5IYBdhLWcg3wOyD9#30498126 - Keval Bhatt
4
令人失望的是,像这样的问题最终会吸引一堆平庸第三方软件包的广告。我不得不筛选出半打这样的“答案”,最终才确定这是不可能的。 - Emperor Eto
13个回答

154

警告框是一个系统对象,不受CSS的影响。要实现这种样式,您需要创建一个HTML元素并模拟alert()功能。jQuery UI对话框为您完成了大部分工作,基本上就像我所描述的:链接

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Dialog - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    $( "#dialog" ).dialog();
  } );
  </script>
</head>
<body>
 
<div id="dialog" title="Basic dialog">
  <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
 
 
</body>
</html>


25
请注意,jQueryUI模态框不会像alert一样暂停JQuery代码的执行等待用户单击。 - T30
3
处理这个问题的好方法是在事件处理程序中包含"event.preventDefault()"。 - PCasagrande
1
你可以使用纯JS创建一个警告框。https://dev59.com/AWox5IYBdhLWcg3wOyD9#30498126 - Keval Bhatt

82

我使用SweetAlert,它非常棒,您将获得很多自定义选项以及所有回调函数。

Screenshot

swal("Here's a message!", "It's pretty, isn't it?");

enter image description here


1
我们能在纯JavaScript和HTML中使用这个吗? - Sukanya Pai
2
sweetalert存在太多问题,而且最后一次发布已经是2年前了,请查看sweetalert 2 - https://sweetalert2.github.io/ - Germa Vinsmoke

71

我尝试使用脚本来为alert()框添加样式,使用了JavaScript。这里我使用了这些JS和CSS。

参考这段代码中的JS功能。

var ALERT_TITLE = "Oops!";
var ALERT_BUTTON_TEXT = "Ok";

if(document.getElementById) {
    window.alert = function(txt) {
        createCustomAlert(txt);
    }
}

function createCustomAlert(txt) {
    d = document;

    if(d.getElementById("modalContainer")) return;

    mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
    mObj.id = "modalContainer";
    mObj.style.height = d.documentElement.scrollHeight + "px";

    alertObj = mObj.appendChild(d.createElement("div"));
    alertObj.id = "alertBox";
    if(d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px";
    alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px";
    alertObj.style.visiblity="visible";

    h1 = alertObj.appendChild(d.createElement("h1"));
    h1.appendChild(d.createTextNode(ALERT_TITLE));

    msg = alertObj.appendChild(d.createElement("p"));
    //msg.appendChild(d.createTextNode(txt));
    msg.innerHTML = txt;

    btn = alertObj.appendChild(d.createElement("a"));
    btn.id = "closeBtn";
    btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT));
    btn.href = "#";
    btn.focus();
    btn.onclick = function() { removeCustomAlert();return false; }

    alertObj.style.display = "block";

}

function removeCustomAlert() {
    document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
}

使用CSS控制alert()弹窗样式

#modalContainer {
    background-color:rgba(0, 0, 0, 0.3);
    position:absolute;
    width:100%;
    height:100%;
    top:0px;
    left:0px;
    z-index:10000;
    background-image:url(tp.png); /* required by MSIE to prevent actions on lower z-index elements */
}

#alertBox {
    position:relative;
    width:300px;
    min-height:100px;
    margin-top:50px;
    border:1px solid #666;
    background-color:#fff;
    background-repeat:no-repeat;
    background-position:20px 30px;
}

#modalContainer > #alertBox {
    position:fixed;
}

#alertBox h1 {
    margin:0;
    font:bold 0.9em verdana,arial;
    background-color:#3073BB;
    color:#FFF;
    border-bottom:1px solid #000;
    padding:2px 0 2px 5px;
}

#alertBox p {
    font:0.7em verdana,arial;
    height:50px;
    padding-left:5px;
    margin-left:55px;
}

#alertBox #closeBtn {
    display:block;
    position:relative;
    margin:5px auto;
    padding:7px;
    border:0 none;
    width:70px;
    font:0.7em verdana,arial;
    text-transform:uppercase;
    text-align:center;
    color:#FFF;
    background-color:#357EBD;
    border-radius: 3px;
    text-decoration:none;
}

/* unrelated styles */

#mContainer {
    position:relative;
    width:600px;
    margin:auto;
    padding:5px;
    border-top:2px solid #000;
    border-bottom:2px solid #000;
    font:0.7em verdana,arial;
}

h1,h2 {
    margin:0;
    padding:4px;
    font:bold 1.5em verdana;
    border-bottom:1px solid #000;
}

code {
    font-size:1.2em;
    color:#069;
}

#credits {
    position:relative;
    margin:25px auto 0px auto;
    width:350px; 
    font:0.7em verdana;
    border-top:1px solid #000;
    border-bottom:1px solid #000;
    height:90px;
    padding-top:4px;
}

#credits img {
    float:left;
    margin:5px 10px 5px 0px;
    border:1px solid #000000;
    width:80px;
    height:79px;
}

.important {
    background-color:#F5FCC8;
    padding:2px;
}

code span {
    color:green;
}

还有一个HTML文件:

<input type="button" value = "Test the alert" onclick="alert('Alert this pages');" />

同时还可以查看这个DEMO: JSFIDDLE和演示结果图片

在此输入图片描述


3
这是自定义警告框,不是原始浏览器警告框的样式。我们是否还缺少一些技巧? - Pratik Joshi
1
答案中的自定义警告框与本地警告框不兼容。本地警告框和提示框是阻塞式等待的。 - Beeno Tung
1
我该如何为确认框做出这个功能? - Lama

11

不可能。如果您想自定义对话框的视觉外观,您需要使用基于JS的解决方案,比如jQuery.UI对话框


8

选项1. 你可以使用 AlertifyJS,这对于警报非常有用。

输入图像描述

输入图像描述

选项2. 你可以启动或加入一个基于Web应用程序的项目,界面设计可能很好。否则,需要进行更改。为了Web 2.0应用程序,你将使用动态内容、许多效果和其他东西。所有这些东西都很好,但没有人考虑过如何样式化JavaScript警报和确认框。以下是方法:

创建一个名为jsConfirmStyle.js的简单JS文件。以下是简单的JS代码。

ie5=(document.getElementById&&document.all&&document.styleSheets)?1:0;
nn6=(document.getElementById&&!document.all)?1:0;

xConfirmStart=800;
yConfirmStart=100;

if(ie5||nn6) {
if(ie5) cs=2,th=30;
else cs=0,th=20;
document.write(
    "<div id='jsconfirm'>"+
        "<table>"+
            "<tr><td id='jsconfirmtitle'></td></tr>"+
            "<tr><td id='jsconfirmcontent'></td></tr>"+
            "<tr><td id='jsconfirmbuttons'>"+
                "<input id='jsconfirmleft' type='button' value='' onclick='leftJsConfirm()' onfocus='if(this.blur)this.blur()'>"+
                "&nbsp;&nbsp;"+
                "<input id='jsconfirmright' type='button' value='' onclick='rightJsConfirm()' onfocus='if(this.blur)this.blur()'>"+
            "</td></tr>"+
        "</table>"+
    "</div>"
);
 }

           document.write("<div id='jsconfirmfade'></div>");


function leftJsConfirm() {
document.getElementById('jsconfirm').style.top=-1000;
document.location.href=leftJsConfirmUri;
}
function rightJsConfirm() {
document.getElementById('jsconfirm').style.top=-1000;
document.location.href=rightJsConfirmUri;
}
function confirmAlternative() {
if(confirm("Scipt requieres a better browser!"))       document.location.href="http://www.mozilla.org";
 }

leftJsConfirmUri = '';
rightJsConfirmUri = '';

/**
 * Show the message/confirm box
*/
function showConfirm(confirmtitle,confirmcontent,confirmlefttext,confirmlefturi,confirmrighttext,confirmrighturi)  {
document.getElementById("jsconfirmtitle").innerHTML=confirmtitle;
document.getElementById("jsconfirmcontent").innerHTML=confirmcontent;
document.getElementById("jsconfirmleft").value=confirmlefttext;
document.getElementById("jsconfirmright").value=confirmrighttext;
leftJsConfirmUri=confirmlefturi;
rightJsConfirmUri=confirmrighturi;
xConfirm=xConfirmStart, yConfirm=yConfirmStart;
if(ie5) {
    document.getElementById("jsconfirm").style.left='25%';
    document.getElementById("jsconfirm").style.top='35%';
}
else if(nn6) {
    document.getElementById("jsconfirm").style.top='25%';
    document.getElementById("jsconfirm").style.left='35%';
}
else confirmAlternative();
}

创建简单的HTML文件
<html>
<head>
<title>jsConfirmSyle</title>
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<script type="text/javascript" src="jsConfirmStyle.js"></script>
<script type="text/javascript">

 function confirmation() {
 var answer = confirm("Wanna visit google?")
 if (answer){
    window.location = "http://www.google.com/";
}
}
  </script>
   <style type="text/css">
    body {
  background-color: white;
   font-family: sans-serif;
  }
#jsconfirm {
border-color: #c0c0c0;
border-width: 2px 4px 4px 2px;
left: 0;
margin: 0;
padding: 0;
position: absolute;
top: -1000px;
z-index: 100;
}

#jsconfirm table {
background-color: #fff;
border: 2px groove #c0c0c0;
height: 150px;
width: 300px;
}

#jsconfirmtitle {
background-color: #B0B0B0;
font-weight: bold;
height: 20px;
text-align: center;
}

#jsconfirmbuttons {
height: 50px;
text-align: center;
}

#jsconfirmbuttons input {
background-color: #E9E9CF;
color: #000000;
font-weight: bold;
width: 125px;
height: 33px;
padding-left: 20px;
}

#jsconfirmleft{
background-image: url(left.png);
}

#jsconfirmright{
background-image: url(right.png);
}
</style>

 <p>
<a href="#"  onclick="javascript:showConfirm('Please confirm','Are you really sure to visit google?','Yes','http://www.google.com','No','#')">JsConfirmStyled</a> </p>
<p><a href="#" onclick="confirmation()">standard</a></p>


</body>
 </html>

7
您需要创建自定义的警告框,就像这样:

function jAlert(text, customokay){
 document.getElementById('jAlert_content').innerHTML = text;
    document.getElementById('jAlert_ok').innerHTML = customokay;
    document.body.style.backgroundColor = "gray";
    document.body.style.cursor="wait";
}



jAlert("Stop! Stop!", "<b>Okay!</b>");
#jAlert_table, #jAlert_th, #jAlert_td{
    border: 2px solid blue;
    background-color:lightblue;
    border-collapse: collapse;
    width=100px;
}

#jAlert_th, #jAlert_td{
    padding:5px;
    padding-right:10px;
    padding-left:10px;
}

#jAlert{
    /* Position fixed */
    position:fixed;
    /* Center it! */
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -100px;
}
<p>TEXT</p>
<div id="jAlRem">
    <div id="jAlert">
        <table id="jAlert_table">
            <tr id="jAlert_tr">
                <td id="jAlert_td">  <p id="jAlert_content"></p>  </td>
                <td id="jAlert_td">  <button id='jAlert_ok'  onclick="jAlertagree()"></button>  </td>
            </tr>
        </table>
    </div>
</div>





<p>TEXT</p>
<p>TEXT</p>
<p>TEXT</p>
<p>TEXT</p>
<p>TEXT</p>
<p>TEXT</p>
<p>TEXT</p>
<p>TEXT</p>
<p>TEXT</p>
<p>TEXT</p>
<p>TEXT</p>
<p>TEXT</p>


<script>
function jAlertagree(){
    var parent = document.getElementById('jAlRem');
    var child = document.getElementById('jAlert');
    parent.removeChild(child);
    document.body.style.backgroundColor="white";
    document.body.style.cursor="default";
}
</script>

这部分js代码用于获取HTML中的元素来创建警告框,然后在用户点击“确定”后将其删除。

您可以使用jAlert("自定义文本", "确定!");调用警告框。


+1 不错的样例,将 width=100px; 编辑为 width:100px; 并使用类代替 ID,#jAlert_th 从未被使用过。 - a55
@a55 是的,所有的观点都是正确的。我必须承认,这篇文章是我五年前刚开始接触网站开发时写的。 - Stardust

6

一种选择是使用altertify,这会提供一个漂亮的警告框。

只需从此处包含所需的库,然后使用以下代码显示警告框。

alertify.confirm("This is a confirm dialog.",
  function(){
    alertify.success('Ok');
  },
  function(){
    alertify.error('Cancel');
  });

输出结果将如下所示。这里是 演示

enter image description here


5

我知道这是一个旧帖子,但今天早上我在寻找类似的东西。 看了一些其他解决方案后,我觉得我的解决方案更简单。 有一点是我在锚标签中使用了字体图标。

我想在用户单击事件时在我的日历上显示一个事件。所以我编写了一个单独的 <div> 标签,如下所示:

<div id="eventContent" class="eventContent" style="display: none; border: 1px solid #005eb8; position: absolute; background: #fcf8e3; width: 30%; opacity: 1.0; padding: 4px; color: #005eb8; z-index: 2000; line-height: 1.1em;">
        <a style="float: right;"><i class="fa fa-times closeEvent" aria-hidden="true"></i></a><br />
        Event: <span id="eventTitle" class="eventTitle"></span><br />
        Start: <span id="startTime" class="startTime"></span><br />
        End: <span id="endTime" class="endTime"></span><br /><br />
</div>

我发现在使用asp.net时,在我的jquery中使用类名更容易。

以下是我的fullcalendar应用的jquery代码。

<script>
    $(document).ready(function() {
        $('#calendar').fullCalendar({
            googleCalendarApiKey: 'APIkey',
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,agendaWeek,agendaDay'
            },
            events: {
                googleCalendarId: '@group.calendar.google.com'
            },
            eventClick: function (calEvent, jsEvent, view) {
                var stime = calEvent.start.format('MM/DD/YYYY, h:mm a');
                var etime = calEvent.end.format('MM/DD/YYYY, h:mm a');
                var eTitle = calEvent.title;
                var xpos = jsEvent.pageX;
                var ypos = jsEvent.pageY;
                $(".eventTitle").html(eTitle);
                $(".startTime").html(stime);
                $(".endTime").html(etime);
                $(".eventContent").css('display', 'block');
                $(".eventContent").css('left', '25%');
                $(".eventContent").css('top', '30%');
                return false;
            }
        });
        $(".eventContent").click(function() {
            $(".eventContent").css('display', 'none');
        });
    });
</script>

您需要拥有自己的Google日历ID和API密钥。

希望这可以帮助您在需要简单弹出显示时使用。


4
回答问题晚一点没有问题。保持更新的答案很重要。 - dckuehn

4

我使用 sweetalert2 库。它非常简单易用,可以进行大量自定义,拥有现代化的、动画效果突出的界面设计,引人注目,同时也很美观。

Swal.fire({
  icon: 'error',
  title: 'Oops...',
  text: 'Something went wrong!',
  footer: '<a href>Why do I have this issue?</a>'
})

请查看此链接


3

<head>
  

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  
    <script type="text/javascript">
  

$(function() {
    $( "#dialog" ).dialog({
      autoOpen: false,
      show: {
        effect: "blind",
        duration: 1000
      },
      hide: {
        effect: "explode",
        duration: 1000
      }
    });
 
    $( "#opener" ).click(function() {
      $( "#dialog" ).dialog( "open" );
    });
  });
    </script>
</head>
<body>
   <div id="dialog" title="Basic dialog">
   <p>This is an animated dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
  </div>
 
  <button id="opener">Open Dialog</button>

</body>


美妙的!!!! - Acca Emme

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接