简体   繁体   English

如何从此代码自定义移动和桌面显示的警报框?

[英]How can I customised alert boxes for both mobile and desktop display from this code?

I am quite new to JS and, although enjoying, am finding it difficult to get syntax correct.我对 JS 很陌生,虽然很享受,但我发现很难让语法正确。

I wanted to customise my alert boxes with my own version of them, and it seemed easy enough.我想用我自己的版本自定义我的警报框,这似乎很容易。 I found a neat tutorial here and ran it successfully, did a bit of styling and found it wasn't very mobile friendly.我在这里找到了一个简洁的教程并成功运行了它,做了一些样式,发现它不是很适合移动设备。

The main issue stems from two parts of the code, CSS here:主要问题源于代码的两部分,这里的 CSS:

    #dialogbox {
  display: none;
  position: fixed;
  background: #0b6623;
  border-radius: 7px;
  width: 550px;
  z-index: 2001;
}

Firstly, the dialogue box is set to 550px, which is fine on a large screen.首先,对话框设置为550px,在大屏幕上没问题。 The real issue occurs when you run the script which sets the position of the dialogue box:当您运行设置对话框位置的脚本时,会出现真正的问题:

function CustomAlert(){
    this.render = function(dialog){
        let winW = window.innerWidth;
        let winH = window.innerHeight;
        let dialogoverlay = document.getElementById('dialogoverlay');
        let dialogbox = document.getElementById('dialogbox');
        dialogoverlay.style.display = "block";
        dialogoverlay.style.height = winH+"px";
        dialogbox.style.left = (winW/2) - (550 * .5)+"px";
        dialogbox.style.top = "100px";
        dialogbox.style.display = "block";
        document.getElementById('dialogboxhead').innerHTML = '<strong>Share your score to Facebook</strong>';
        document.getElementById('dialogboxbody').innerHTML = dialog;
        document.getElementById('dialogboxfoot').innerHTML = '<button class="btn btn-danger" onclick="Alert.ok()"><i class="far fa-times-circle"></i> Close</button>';
    }
    this.ok = function(){
        document.getElementById('dialogbox').style.display = "none";
        document.getElementById('dialogoverlay').style.display = "none";
    }
}
let Alert = new CustomAlert();

There are lines there that set the box directly into the centre of the screen.那里有一些线条将框直接设置在屏幕的中心。

My question is - I still want centre screen but I want the dialogue box to be fluid and shrink down to size on a mobile phone.我的问题是 - 我仍然想要中央屏幕,但我希望对话框流畅并缩小到手机上的大小。 Does anyone have suggestions on how to do this with that CSS?有没有人有关于如何使用该 CSS 执行此操作的建议?

The full script is available here: https://www.developphp.com/video/JavaScript/Custom-Alert-Box-Programming-Tutorial完整脚本可在此处获得: https : //www.developphp.com/video/JavaScript/Custom-Alert-Box-Programming-Tutorial

Thanks kindly :)多谢:)

Okay last attempt to help here.好的,最后一次尝试在这里提供帮助。 The sample code below behaves exactly the same as the built in browser alert dialog boxes.下面的示例代码的行为与内置的浏览器警报对话框完全相同。 It puts the box in the middle, auto sizes according to the content, and anything else on the page is NOT clickable or editable until the dialog box is closed.它将框放在中间,根据内容自动调整大小,并且页面上的任何其他内容在对话框关闭之前都是不可点击或可编辑的。 Well I wrote is a while back and I don't see any difference.好吧,我写了一段时间,我看不出有什么区别。 It should work on any device so use it, change it, style it however you want.它应该适用于任何设备,因此可以根据需要使用它、更改它、设置样式。 Note the "DO NOT CHANGE" comments.请注意“请勿更改”注释。 Changing that defeats the purpose.改变它违背了目的。 You do need the JQuery.js so download the the latest one here https://jquery.com/download/ .您确实需要 JQuery.js,因此请在此处下载最新的https://jquery.com/download/

<!DOCTYPE html>
<html lang="en">
<head>
<style type="text/css">
    
    .main-container{
        display: flex;    /* DO NOT CHANGE */
        height: 100vh;    /* DO NOT CHANGE */
        width: 100%;      /* DO NOT CHANGE */
    }

    .c-message{
        display: flex;    /* DO NOT CHANGE */
        position: fixed;  /* DO NOT CHANGE */
        top: 0px;         /* DO NOT CHANGE */
        left: 0px;        /* DO NOT CHANGE */
        width: 100%;      /* DO NOT CHANGE */
        height: 100%;     /* DO NOT CHANGE */
    }

    .c-msgbox{
        padding: 30px;
        text-align: center;
        margin: auto; /* DO NOT CHANGE */
        background-color: #e4e4e4;
        border-radius: 4px;
        border: 1px solid #adadad;
        -webkit-box-shadow: 0px 0px 50px rgba(0, 0, 0, 0.60);
        -moz-box-shadow: 0px 0px 50px rgba(0, 0, 0, 0.60);
        box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.40);
    }

    .standerd-button2{
        border: none;
        font-family: arial,helvetica,clean,sans-serif;
        font-size: 10px;
        font-weight: 600;
        color: white;
        background: #1A709F;
        padding: 3px;
        text-align: center;
        vertical-align: middle;
        -webkit-border-radius: 3px;
        width: max-content;
        min-width: 50px;
        margin: 2px;
    }

    .standerd-button2:hover{
        background: crimson;
        cursor: default;
    }

</style>
<script type="text/javascript" src="JQuery.js"></script>
</head>
<body>
<div class="main-container">
    <div>
        <a id="ok" href="#">Normal Alert</a>
        <br>
        <a id="yn" href="#">Yes/No Alert</a>
    </div>
<div>
<script type="text/javascript">

    $.fn.CustomAlert = function (options, callback) {
        var settings = $.extend({
            message: null,
            detail: null,
            yesno: false,
            okaytext: null,
            yestext: null,
            notext: null
        }, options);

        var frm = "";
        detail = "<b>" + settings.detail + "</b>";
        message = "<b>" + settings.message + "</b>";
        if (settings.detail === null) {
            detail = "";
        };

        frm = frm + message + "<div style='text-align: left; margin-top: 15px; margin-bottom: 15px;'>" + detail + "</div>";

        if (settings.yesno === false) {
            frm = frm + "<input id='ok' type='button' value='" + settings.okaytext + "' class='standerd-button2' />";
        } else {
            frm = frm + "<div><input id='yes' type='button' value='" + settings.yestext + "' name='yes' class='standerd-button2' />" +
                        "<input id='no' type='button' value='" + settings.notext + "' name='no' class='standerd-button2' /></div>";
        };

        var frmesg = "<div id='cmessage' name='cmessage' class='c-message'>" +
                     "<div class='c-msgbox'>" +
                     "<form>" + frm + "</form>" +
                     "</div>" +
                     "</div>";

        $(".main-container").append(frmesg);

        if (!settings.yesno) {
            $("#cmessage #ok").click(function () {
                $("#cmessage").remove();
                callback(false);
            });
        } else {
            $("#cmessage #yes").click(function () {
                $("#cmessage").remove();
                callback(true);
            });
            $("#cmessage #no").click(function () {
                $("#cmessage").remove();
                callback(false);
            });
        };
    };

    $("#yn").click(function(){
        $().CustomAlert({message: "<div style='text-align: left;'><p><b>Confirmation Alert</b></p></div>",
                       yestext: "Yes",
                       notext: "No",
                       yesno: true},
                       function(success){
                           if (success) {
                               null;
                               // Do something
                           } else {
                               null;
                               // Do something else
                               
                       };
        });
    });

    $("#ok").click(function(){
        $().CustomAlert({message: "<div style='text-align: left;'><p><b>Bla bla bla</b></p></div>",
                       okaytext: "Continue",
                       yesno: false},
                       function(success){
                           if (success) {
                               null;
                               // Do something
                        
                       };
        });
    });    
</script>
</body> 

You can use Media Queries.您可以使用媒体查询。 Give your modal dialog a different style on mobile, tablet and desktop if needed.如果需要,在移动设备、平板电脑和桌面设备上为您的模态对话框提供不同的样式。 https://www.w3schools.com/css/css_rwd_mediaqueries.asp https://www.w3schools.com/css/css_rwd_mediaqueries.asp

@media only screen and (min-width: 480px) {
 #dialogbox {
    /* your mobile styles */
  }
}

@media only screen and (min-width: 720px) {
 #dialogbox {
     /* your mobile styles */
  }
}

#dialogbox {
     /* your normal styles */
  }

Use vh and vw.使用 vh 和 vw。 These are view width and height, relative to the browser window.这些是相对于浏览器窗口的视图宽度和高度。 One unit equals 1% of the browser width or height.一个单位等于浏览器宽度或高度的 1%。

Use vh and vw if you want to set specific width and heights.如果要设置特定的宽度和高度,请使用 vh 和 vw。 But I would suggest having all your content in a main div with a css style "display: flex;"但我建议将您的所有内容都放在一个带有 css 样式"display: flex;"的主 div 中"display: flex;" and your actual dialogue box(div) size not specified but just with a css property of "margin: auto;"并且您的实际对话框(div)大小未指定,但仅具有"margin: auto;"的css属性. .

This will center it and automatically be sized according to your content in the box.这将使其居中并根据您在框中的内容自动调整大小。 But then again, if you want to specify a size you can still then use vw and vh.但话又说回来,如果你想指定一个大小,你仍然可以使用 vw 和 vh。 Up to you.由你决定。

I stuck with this function in JS but removed one line and its variable:我在 JS 中坚持使用这个函数,但删除了一行及其变量:

let winW = window.innerWidth;
    dialogbox.style.left = (winW/2) - (550 * .5)+"px";

The CSS had some changes too: CSS 也有一些变化:

#dialogbox {
  display: none;
  position: fixed;
  margin-top: 17.5%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #0b6623;
  border-radius: 7px;
  width: 67.7%;
  max-width: 550px;
  z-index: 2001;
}

It's not perfect, granted, but it is 10s of 1000s of times better than before.这并不完美,当然,但它比以前好 10 到 1000 倍。

For those wondering why a z-index of 2001, because I am using bootstrap modals and they have a z-index of 1040 or so.对于那些想知道为什么 z-index 为 2001 的人,因为我使用的是引导模式并且它们的 z-index 为 1040 左右。 And the z-index of 2000 is taken up by the white overlay (see code in OP).并且 2000 的 z-index 被白色覆盖层占用(参见 OP 中的代码)。

This is what I suggest, if what I think you want is correct.这就是我的建议,如果我认为你想要的是正确的。 Copy this below and test it.复制下面这个并测试它。 If it is not what you need, sorry, just tried to help.如果这不是您所需要的,抱歉,只是试图提供帮助。

<!DOCTYPE html>
<html lang="en">
<head>
<style type="text/css">
    
*{
    margin: 0;
    padding: 0;
}

.main-container{
    display: flex;
    height: 100vh;
    width: 100%;
}

.dialogbox{
    display: flex; 
    margin: auto;
    padding: 20px;
    border-radius: 4px;
    border: 1px solid #adadad;
    -webkit-box-shadow: 0px 0px 50px rgba(0, 0, 0, 0.60);
    -moz-box-shadow: 0px 0px 50px rgba(0, 0, 0, 0.60);
    box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.40);    
}

.dialogbox .dialogtext{
    margin: auto;
}

</style>
</head>
<body>
<div class="main-container">
    <div class="dialogbox">
        <span class="dialogtext">
            <h3>Some text</h3>
        </span> 
    </div>  
<div>
</body> 

Note: this answer has become somewhat discursive, in terms of answering the question as set, the use of CSS vw/vh and media queries as recommended by other contributors will solve the immediate problem.注意:这个答案已经变得有些散漫,在回答问题方面,使用其他贡献者推荐的 CSS vw/vh 和媒体查询将解决眼前的问题。 I have left this answer here though as pondering the question raised additional issues of 'what are we trying to do with an alert function?'我已经把这个答案留在这里了,因为思考这个问题引发了“我们试图用警报功能做什么?”的额外问题。

The alert function in Javascript has some characteristics that you cannot emulate in your own Javascript, but you can get close. Javascript 中的alert 函数有一些你无法在你自己的Javascript 中模仿的特性,但你可以接近。

The main thing about alert is that it is just that, the user is informed no matter what else is going on so it sits on top.关于警报的主要事情就是这样,无论发生什么事情都会通知用户,因此它位于最前面。 It can get 'lost' in the middle of a wide window if the window is partially off the screen.如果窗口部分离开屏幕,它可能会在宽窗口中间“丢失”。

On most mobiles though it's a bit better because normally if your code is running the window will be at least partially visible on the screen.尽管在大多数手机上它会好一点,因为通常如果您的代码正在运行,窗口将至少部分显示在屏幕上。

For your immediate question, the best bet for making the alert box be visible, is to use the viewport dimensions plus fixed (as you have done)- the given code uses window dimensions and that just isn't going to work in all cases - the alert box could be way off the screen - for example if the window is representing a long scroll which the user is scrolling through.对于您当前的问题,使警报框可见的最佳选择是使用视口尺寸加上固定尺寸(正如您所做的那样)- 给定的代码使用窗口尺寸,并且在所有情况下都不起作用-警报框可能远离屏幕 - 例如,如果窗口代表用户正在滚动的长滚动。

Second you want the box to be visible above anything else that's in your window, so setting the z-index in CSS to something higher than you will ever use in the rest of your code is needed.其次,您希望该框在窗口中的任何其他内容上方可见,因此需要将 CSS 中的 z-index 设置为高于您将在其余代码中使用的值。 (Does anyone know if all browsers would accept Number.MAX_SAFE_INTEGER - for ultimate safety though that would be quite extreme) (有谁知道是否所有浏览器都接受 Number.MAX_SAFE_INTEGER - 为了最终的安全,尽管这会非常极端)

Third you need to fix the alert box in the viewport so the user can't scroll away from it - you want the user to respond so you know they have seen the message and can't completely ignore it.第三,您需要修复视口中的警告框,以便用户无法滚动离开它 - 您希望用户做出响应,以便您知道他们已经看到了消息并且不能完全忽略它。

Fourth is the question of blocking.第四是阻塞问题。 A JS alert does this, but is it wise to have our own function do it and/or replace the native alert totally with our own function. JS 警报可以做到这一点,但让我们自己的函数来做这件事和/或用我们自己的函数完全替换原生警报是否明智。 Probably not, at some point you may want the real alert to work so might be best to leave it alone.可能不会,在某些时候您可能希望真正的警报起作用,因此最好不要管它。

Replacing window.width with vw will make the box responsive - but it could be unreadable at small screens or not large enough on enormous ones.用 vw 替换 window.width 将使框响应 - 但它可能在小屏幕上不可读或在大屏幕上不够大。 Fortunately CSS has media queries so you can use them with breakpoints at the most common sizes of screen to decide the width of your alert box (you need to let the height be scrollable as you don't know how much info is to be shown).幸运的是,CSS 具有媒体查询,因此您可以将它们与最常见屏幕尺寸的断点一起使用来决定警报框的宽度(您需要让高度可滚动,因为您不知道要显示多少信息) .

Note: the code below uses different naming from the original question to prevent confusion as the use of some of the elements is slightly different.注意:下面的代码使用与原始问题不同的命名以防止混淆,因为某些元素的使用略有不同。

Moving the styling and especially the sizing decisions totally to CSS the JS can become something like:将样式,尤其是大小决定完全转移到 CSS 中,JS 可以变成这样:

function myAlert(alertMessage){
        document.getElementById('alertinfo').innerHTML = alertMessage;
        document.getElementById('alertoverlay').style.display = "block";
}
function myRemove(event) {
        event.preventDefault();
        event.stopPropagation();
        document.getElementById('alertoverlay').style.display = 'none';
}

CSS CSS

#alertoverlay {
    position: fixed;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    z-index: 999999;
    background-color: rgba(0,0,0,0.2);
    overflow: hidden;
    display: none;
}

#alertbox {
    font-family: Arial, Helvetica, sans-serif;
    width : 100vw;
    height: auto;
    overflow-y: auto;
    position: fixed;
    font-size: 10px; 
    background-color: white;
    text-align: center;
}

#alertheader {
    font-size: 3em;
}

#alertinfo {
    margin-top: 20px;
}

#alertokbox {
    width: 44px;
    height: 44px !important;
    float: right;
    margin: 10px;
    border-style: solid;
    border-radius: 10%;
    vertical-align: center;
}

#alertok {
    margin-top: 14px;
}

@media only screen and (min-width: 550px) {
  #alertbox {
    width: 550px;
    left: 50vw;
    margin-left: -275px;
    font-size: 16px;
  }
}

@media only screen and (min-width: 1600px) {
  #alertbox {
    width: 30vw;
    left: 50vw;
    margin-left: -15vw;
    font-size: 1vw;
  }
}

HTML HTML

<div id="alertoverlay">
  <div id="alertbox">
    <div id="alertheader">Alert</div>
    <div id="alertinfo"></div>
    <div id="alertokbox" onclick="myRemove(event);"></div>
    <div id="alertok">OK</div>
  </div>
</div>

You can have as many media 'breakpoints' as you like - for example if you are coding for a huge display screen right down to the smallest smart phone you will need to think about just how big you want your box to be.您可以拥有任意数量的媒体“断点”——例如,如果您正在为一个巨大的显示屏编码,甚至最小的智能手机,您将需要考虑您希望您的盒子有多大。

For centering to work (the left and margin-left settings in the CSS) you will need to have the alert box in a div which is fixed with width the width of the screen - so left: 0;为了使居中工作(CSS 中的 left 和 margin-left 设置),您需要在 div 中放置警报框,该 div 的宽度固定为屏幕宽度 - 所以 left: 0; right: 0;右:0;

 <!DOCTYPE html> <html> <head> <style> #alertoverlay { position: fixed; left: 0; top:0; bottom:0; right:0; z-index: 999999; background-color: rgba(0,0,0,0.2); overflow: hidden; display:none; } #alertbox { font-family: Arial, Helvetica, sans-serif; width : 100vw; height: auto; overflow-y: auto; position: fixed; font-size: 10px; background-color:white; text-align:center; } #alertheader { font-size: 3em; } #alertinfo { margin-top: 20px; } #alertokbox { width:44px; height: 44px !important; float:right; margin: 10px; border-style: solid; border-radius: 10%; vertical-align:center; } #alertok { margin-top:14px; } @media only screen and (min-width: 550px) { #alertbox { width: 550px; left:50vw; margin-left:-275px; font-size: 16px; } } @media only screen and (min-width: 1600px) { #alertbox { width: 30vw; left: 50vw; margin-left: -15vw; font-size: 1vw; } } #application { width:2000px; height:2000px; background-color: white; } </style> </head> <body> <div id="application"> <button onclick="myAlert('Read this important message then click OK');">Click me to show an alert</button> </div> <div id="alertoverlay"> <div id="alertbox"> <div id="alertheader">Alert</div> <div id="alertinfo"></div> <div id="alertokbox" onclick="myRemove(event);"><div id="alertok">OK</div></div> </div> </div> <script> function myAlert(alertMessage){ document.getElementById('alertinfo').innerHTML = alertMessage; document.getElementById('alertoverlay').style.display = "block"; } function myRemove(event) { event.preventDefault(); event.stopPropagation(); document.getElementById('alertoverlay').style.display='none'; } </script> </body> </html>

Okay.好的。 This part is the function这部分是功能

    $.fn.CustomAlert = function (options, callback) {
        var settings = $.extend({
            message: null,
            detail: null,
            yesno: false,
            okaytext: null,
            yestext: null,
            notext: null
        }, options);
     ....
     ....

As you can see it takes a few parameters.如您所见,它需要一些参数。 1) Is the message that will be centered. 1) 是将要居中的消息。 2) Message detail(optional that will be aligned to the left. 3) yesno is either true or false. 2) 消息详细信息(可选,将向左对齐。3) yesno 为真或假。 True for confirmation dialog or false for just an ok dialog.确认对话框为真,仅确定对话框为假。 4) okaytext is usually "Okay" or "Continue" if yesno is false. 4) 如果 yesno 为假,okaytext 通常为“好的”或“继续”。 5) yestext is usually "Yes" if yesno is true. 5) 如果 yesno 为真, yestext 通常为“是”。 6) notext is usually "No if yesno is true. All are optional but with a little logic you will figure out what to pass when. The following is the click event and then the function call. 6) notext 通常是“No if yesno is true。所有都是可选的,但通过一点逻辑你会弄清楚什么时候通过。以下是点击事件,然后是函数调用。

    $("#yn").click(function(){
        $().CustomAlert({message: "<div style='text-align: left;'><p><b>Confirmation Alert</b></p></div>",
                       yestext: "Yes",
                       notext: "No",
                       yesno: true},
                       function(success){
                           if (success) {
                               null;
                               // Do something
                           } else {
                               null;
                               // Do something else
                               
                       };
        });
    });

$("#yn").click(function(){ // This is the event when that anchor with the id of "yn" is clicked. By the parameters you can also see that it is confirmation dialog. Make sense? $("#yn").click(function(){ // 这是id为"yn"的anchor被点击的事件,通过参数也可以看出是确认对话框。有意义吗?

I recommend spending a little time learning JQuery.我建议花一点时间学习 JQuery。 It is not so difficult and very powerful.它并不那么困难,而且非常强大。 It saves you a lot of coding.它为您节省了大量编码。 Took me less then a day, and that just from w3schoole.花了我不到一天的时间,而这只是来自 w3schoole。 Try not using the plugins and JQuery UI.尽量不要使用插件和 JQuery UI。 Rather write your own plugins as I did.而是像我一样编写自己的插件。 This code is all from my lib.这段代码全部来自我的库。 It just helps to understand it better.它只是有助于更好地理解它。 Also I do not recommend using bootstrap, not that there is anything wrong with it, but doing your own CSS3 stylesheets empowers you to what you want.另外我不推荐使用 bootstrap,并不是说它有什么问题,但是做你自己的 CSS3 样式表可以让你得到你想要的。 That is just my opinion.这只是我的意见。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在移动浏览器的屏幕顶部显示自定义提醒? - How can I display a custom alert at the top of the screen on a mobile browser? 如何将电话号码显示为移动设备而不是桌面设备上的链接? - How can I display a phone number as a link on mobile but not desktop? 如何通过链接到桌面和移动设备上包含 HTML 代码的一个文档,在多个 HTML 文档中显示我的导航栏代码? - How can I display my Navbar Code in multiple HTML documents by linking to one document containing the HTML Code on Desktop and Mobile? 如何通过我的 HTML 或 JavaScript 代码在移动设备上强制桌面视图 - How can I Force desktop view on a mobile device from my HTML or JavaScript code 我怎样才能让这个评级组件自动居中移动和桌面版本? - How can I get this rating component automatically centered for both mobile and desktop version? 怎么做 <iframe> 在wordpress中响应。 我只能在移动设备或桌面设备上做出响应。 需要它在两者中都运作良好 - how to make <iframe> responsive in wordpress. I can only make it responsive in either mobile or in desktop. need it to work well in both 如何显示背后代码的警报消息? - How to display alert message from code behind ? 如何获取警报框和验证处理此代码 - How to get alert boxes and validation working on this code 如何使用PageSpeed获得移动和桌面得分 - How to get both mobile and desktop score with PageSpeed 如何自定义 Ant 设计的表格? - How can I customised the form of Ant Design?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM