程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

How to make custom prompt boxes within functions in JavaScript? [duplicate]

发布于2023-11-12 16:49     阅读(510)     评论(0)     点赞(7)     收藏(1)


I started coding a button program about a week ago, and have made quite a bit of progress. I'm new to HTML, CSS and JS, but seem to be learning quite quickly. The thing I want to do next, is create a custom prompt + alert box for my code, but I can't figure out how to do it within functions. This is my code:

<!doctype html>

<head>

<title> Testing Buttons with JS</title>

<style>
body {
    background-color: lightblue;
}

.button {
    background-color: #4CAF50; /* Green */
    border-color: white;
    color: white;
    padding: 20px 20px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 13px;
}
</style>

<script>

function milestokm()
{
  var miles = prompt("Enter distance in miles.");
  if (miles == parseInt(miles) || (miles == parseFloat(miles))) {
    window.alert(miles + " miles is " + (1.61*miles).toFixed(2) + " km.");   
  }
  else {
      window.alert("Input is not a valid number.");
    }
}   


function addxno() 
{ 
    var numbers = [];
    var torun = Number(prompt("Enter how many numbers you wish to add?"));
    for (var counter=0; counter < torun ; counter = counter + 1) 
    {  
        number = Number(prompt("Enter a number"));
        if (number === parseInt(number, 10) || (number === parseFloat(number, 10))) {
          numbers.push(number);
        }
        else {
          window.alert("Input was an invalid number so won't be added to other numbers.");
        }
    }
    var sum = numbers.reduce(add, 0);

    function add(a, b) {
        return a + b;
    }
    alert("The sum of " + numbers + " is: " + sum);
}


function mulxno()
{ 
    var numbers = [];
    var torun = Number(prompt("Enter how many numbers you wish to multiply?"));
    for (var counter=0; counter < torun ; counter = counter + 1) 
    {  
      number = Number(prompt("Enter a number"));
      if (number === parseInt(number, 10) || (number === parseFloat(number, 10))) {
        numbers.push(number);
      }
      else {
        window.alert("Input was an invalid number so won't be multiplied by the other numbers.");
      }
    }
    var sum = numbers.reduce(times);

    function times(a, b) {
        return a * b;
    }
    alert("The numbers " + numbers + " multiplied together gives a result of: " + sum);
}


function subxno() 
{
    var numbers = [];
    var torun = Number(prompt("Enter how many numbers you wish to subtract?"));
    for (var counter=0; counter < torun ; counter = counter + 1) 
    {  
      number = Number(prompt("Enter a number"));
      if (number === parseInt(number, 10) || (number === parseFloat(number, 10))) {
        numbers.push(number);
      }
      else {
        window.alert("Input was an invalid number so won't be subtracted from the other numbers.");
      }
    }
    var sum = numbers.reduce(times);

    function times(a, b) {
        return a - b;
    }
    alert("The numbers " + numbers + " subtracted from eachother gives a result of: " + sum);
}


function avexno()
{
    var numbers = [];
    var torun = Number(prompt("How many numbers do you wish to find the average of?"));
    for (var counter=0; counter < torun ; counter = counter + 1) 
    {  
      number = Number(prompt("Enter a number"));
      if (number === parseInt(number, 10) || (number === parseFloat(number, 10))) {
        numbers.push(number);
      }
      else {
        window.alert("Input was an invalid number so the average won't be effected from this input.");
      }
    }
    var sum = numbers.reduce(times);

    function times(a, b) {
        return a + b;
    }

    average = (sum/torun)
    if (average === parseInt(average, 10)) {
        alert("The average of " + numbers + " is: " + average);
    }
    else {
        alert("The average of " + numbers + " is: " + (average.toFixed(2)));
    }
}


function moneyconverter()
{   
    choice = prompt("Do you wish to convert:\na) GBP to USD\nb) USD to GBP");
    if (choice == "a") {
        var pounds = Number(prompt("Enter amount of GB Pounds (£)."));
        var dollars = Number(pounds*1.33);
        dollars = dollars.toFixed(2);
        window.alert("£" + pounds + " is ≈ $" + dollars + "!");
    }
    else if (choice == "b") {
        var dollars = Number(prompt("Enter amount of US Dollars. ($)."));
        var pounds = Number(dollars/1.33);
        pounds = pounds.toFixed(2);
        window.alert("$" + dollars + " is ≈ £" + (pounds) + "!");    
    }
}

function metrestofeet() //Updated to V2 on 25/06/18
{
    var metres = Number(prompt("Enter distance in metres."));
    if (metres === parseInt(metres, 10) || (metres === parseFloat(metres, 10))) {
        if ((metres % 3.28) === 0) {
            window.alert(metres + " metres is " + 3.28*metres + " feet.");
        }
        else {
            window.alert(metres + " metres is " + (3.28*metres).toFixed(2) + " feet.");
        }
    }
    else {
        window.alert("Input is not a valid number.");
    }   
}


function tempconverter() 
{
    var option = prompt("Do you to convert\na)Celsius to fahrenheit\nb)Fahreheit to celsius");
    if (option == "a") {    
        var celsius = Number(prompt("Enter temeperature in Celsius."));
        if (celsius === parseInt(celsius, 10) || (celsius === parseFloat(celsius, 10))) {
            var fahrenheit = ((((celsius*9)/5)+32));
            if (fahrenheit === parseInt(fahrenheit, 10)) {    
                window.alert(celsius + " celsius is: " + fahrenheit);
            }
            else {
                window.alert(celsius + " celsius is: " + fahrenheit.toFixed(2) + " fahrenheit.");
            }
        }
        else {
            window.alert("Input is not a valid number.");
            }
        }
    else if (option == "b") {
        var fahrenheit = Number(prompt("Enter temeperature in Fahrenheit."));
            if (fahrenheit === parseInt(fahrenheit, 10) || (fahrenheit === parseFloat(fahrenheit, 10))) {    
                var celsius = ((((fahrenheit-32)*5)/9));
                if (celsius === parseInt(celsius, 10)) {
                    window.alert(fahrenheit + " fahrenheit is: " + celsius + " celsius.");
                    }
                else {
                    window.alert(fahrenheit + " fahrenheit is: " + celsius.toFixed(2) + " celsius.");
                }
            }
            else {
                window.alert("Input is not a valid number");
       }
    }          
}


function numberposorneg()
{
    var number = Number(prompt("Enter a number."));
    if (number < 0) {
        window.alert(number + " is a negative number.");
    }
    else if (number > 0) {
        window.alert(number + " is a positive number.");
    }
    else {
        window.alert(number + " is neither positive nor negative.");
    }
}


function timeconverter() 
{
    var conversion = Number(prompt("Do you wish to convert:\n1)hours to minutes\n2)minutes to seconds\n3)seconds to minutes\n4)seconds to hours\n5)hours to seconds"));
    if (conversion == 1) {
        var hours = Number(prompt("Enter the amount of hours"));
        window.alert(hours + " hours is " + (hours*60) + " minutes.");
    }


    else if (conversion == 2) {
        var minutes = Number(prompt("Enter the amount of minutes."));
        if (minutes < 1) {
            window.alert("That number is too small");
        }
        else {
            if ((minutes % 60) == 0) { 
                window.alert(minutes + " minutes is " + (minutes*60) + " seconds.");
        }
            else {
                window.alert(minutes + " minutes is " + ((minutes*60).toFixed(2)) + " seconds.");
            }
        }
    }


    else if (conversion == 3) {
        var seconds = Number(prompt("Enter the amount of seconds."));
        if (seconds==60) {
            window.alert(seconds + " seconds is " + (seconds/60) + " minute.");
        }
        else if ((seconds % 60) == 0) {
            window.alert(seconds + " seconds is " + (seconds/60) + " minutes.");
        }
        else {
            window.alert(seconds + " seconds is " + ((seconds/60).toFixed(2)) + " minutes.");
        }
    }


    else if (conversion == 4) {
        var seconds = Number(prompt("Enter the amount of seconds."));
        if (seconds == 3600) {
            window.alert(seconds + " seconds is " + (seconds/3600) + " hour.");
        }
        else if ((seconds % 3600) == 0) {
            window.alert(seconds + " seconds is " + (seconds/3600) + " hours.");
        }
        else {
            window.alert(seconds + " seconds is " + ((seconds/3600).toFixed(2)) + " hours.");
        }
    }
    else if (conversion == 5) { 
      hours = Number(prompt('Enter amount of hours'));
      if (hours === parseInt(hours, 10) || (hours === parseFloat(hours, 10))) {
        seconds = Number(hours*3600);
      if (seconds === parseInt(seconds, 10)) {
        window.alert(hours + ' hours is ' + (hours*3600) + ' seconds.');
      }
      else {
        window.alert(hours + ' hours is ' + ((hours*3600).toFixed(2)) + ' seconds.');
      }
    }
    else {
        window.alert('Input is not a valid number.'); 
    }
  }
}

</script>

<body>
<button class = "button" onclick="timeconverter()"> Time Converter. </button>
<br>
<button class = "button" onclick="addxno()">Add (x) numbers.</button>
<br>
<button class = "button" onclick="moneyconverter()"> Money Converter.</button>
<br>
<button class = "button" onclick="milestokm()">Convert miles to km.</button>
<br>
<button class = "button" onclick="mulxno()">Multiply (x) numbers.</button>
<br>
<button class = "button" onclick="subxno()">Subtract (x) numbers.</button>
<br>
<button class = "button" onclick="metrestofeet()">Convert metres to feet.</button>
<br>
<button class = "button" onclick="tempconverter()">Temperature Converter.</button>
<br>
<button class = "button" onclick="avexno()">Average of (x) numbers.</button>
<br>
<button class = "button" onclick="hourandmintosec()">Hours and minutes to seconds.</button>
<br>
<button class = "button" onclick="numberposorneg()"> Detect whether number is positive or negative.</button>
<br>
</div>
</body>
</html>

As you can see, I’ve got a lot of prompts and alerts, but they’re default and I want to decorate them. Please advise me on how to do this (ideally with an example)


解决方案


You can't edit the css properties of alert box, or any other (prompt/confirm/..) box

That is because alert() itself is a javascript object and not a HTML entity (tag). What you however can do, is to create a hidden div that would imitate alert box and upon EventHandler you would change it's property as visible, which would act like an alert box.

It is an immitation, but that is closest you can get to custom styled alertbox. Often times it's actually a bit more practical than an actual alert()

Here is a (rather ugly) example of it in action:

var btn = document.getElementById('alertbutton');
var alertmsg = document.getElementById('alert');
var okbtn = document.getElementById('okbtn');

btn.addEventListener('click', function(){
  alertmsg.classList.remove('hidden');
  //execute some other code if necessary
  okbtn.addEventListener('click',function(){
    alertmsg.classList.add('hidden');
    // also some other code if necessary
  });
});
#lorem {
  width: 320px;
  height: 320px;
  overflow: hidden;
  background-color: #cecece;
  border: 4px solid black;
  word-wrap: break-all;
}

button {
  position: relative;
  top: -220px;
  left: 350px;
  height: 30px;
}

#alert {
  position: relative;
  width: 60%;
  left: 50%;
  bottom: 40vw;
  transform: translateX(-50%);
  border: 4px solid red;
  padding: 20px;
  background-color: #FF9999;
}

.OK {
  position: absolute;
  display: block;
  float: right;
  right: 30px;
  bottom: 30px;
  height: 40px;
  width: 60px;
}

.hidden {
  display: none;
}
<div id="lorem">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam mauris velit, vulputate sed ante eget, dignissim porttitor mi. Aenean eu metus in enim fermentum iaculis. Vivamus diam nibh, ultricies varius hendrerit eget, rutrum in magna. Curabitur sit
  amet nisl bibendum, pharetra tortor sed, mollis augue. Fusce fringilla pulvinar lacus id sollicitudin. Phasellus lacus diam, hendrerit quis metus eget, feugiat placerat libero. Nunc congue neque sit amet est volutpat, non vestibulum nunc elementum.
  Phasellus tempor ex ac magna imperdiet, quis consectetur nibh posuere. Vivamus cursus est et nisi molestie, sed hendrerit velit blandit. Donec faucibus dapibus pharetra. Maecenas sem nisi, sodales ut tristique non, ultricies eget est.</div> <button id="alertbutton">Display Alert</button>

<div id="alert" class="hidden">
  <h1>Custom alert!</h1> Please click 'OK' to continue <input type="submit" id="okbtn" class="OK" value="OK"/>
</div>




所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:http://www.qianduanheidong.com/blog/article/532552/b0306d5b04e0e41e8c57/

来源:前端黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

7 0
收藏该文
已收藏

评论内容:(最多支持255个字符)