如何在JavaScript函数中创建自定义提示框?

时间:2018-07-02 13:58:36

标签: javascript html css alert prompt

大约一周前,我开始编写按钮程序,并取得了相当大的进步。我是HTML,CSS和JS的新手,但是学习起来似乎很快。接下来要做的是为代码创建一个自定义的提示+警报框,但是我不知道如何在函数中执行此操作。这是我的代码:

<!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>

如您所见,我有很多提示和警报,但是它们是默认的,我想装饰它们。请为我提供有关操作方法的建议(最好是举个例子)

1 个答案:

答案 0 :(得分:0)

您无法编辑alert框或任何其他(prompt/confirm/..)框的css属性

这是因为alert()本身是一个javascript对象,而不是HTML实体(标记)。 但是,您可以做的是创建一个隐藏的div,它会模仿警报框,并在EventHandler上将其属性更改为可见,就像警报框一样。

这是一个模仿,但距离自定义样式的警报框最近。通常,它实际上比实际的alert()

更实用。

这是它的一个(相当丑陋)实例:

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>