JavaScript 弹出框

JavaScript 有三种类型的弹出框:警告框、确认框和提示框。

警告框

若是要确保信息传递给用户,一般会使用警告框。html

当警告框弹出时,用户将须要单击“肯定”来继续。spa

语法

window.alert("sometext");

window.alert() 方法能够不带 window 前缀来写。code

实例

alert("我是一个警告框!");

完整实例

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript 警告框</h1>

<button onclick="myFunction()">试一试</button>

<script>
function myFunction() {
  alert("我是一个警告框!");
}
</script>

</body>
</html>

确认框

若是您但愿用户验证或接受某个东西,则一般使用“确认”框。htm

当确认框弹出时,用户将不得不单击“肯定”或“取消”来继续进行。blog

若是用户单击“肯定”,该框返回 true。若是用户单击“取消”,该框返回 false。ip

语法

window.confirm("sometext");

window.confirm() 方法能够不带 window 前缀来编写。get

实例

var r = confirm("请按按钮");
if (r == true) {
    x = "您按了确认!";
} else {
    x = "您按了取消!";
}

完整实例

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript 确认框</h1>


<button onclick="myFunction()">试一试</button>

<p id="demo"></p>

<script>
function myFunction() {
  var txt;
  if (confirm("Press a button!")) {
    txt = "您按了肯定";
  } else {
    txt = "您按了取消";
  }
  document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>

提示框

若是您但愿用户在进入页面前输入值,一般会使用提示框。io

当提示框弹出时,用户将不得不输入值后单击“肯定”或点击“取消”来继续进行。function

若是用户单击“肯定”,该框返回输入值。若是用户单击“取消”,该框返回 NULL。class

语法

window.prompt("sometext","defaultText");

window.prompt() 方法能够不带 window 前缀来编写。

实例

var person = prompt("请输入您的姓名", "比尔盖茨");
if (person != null) {
    document.getElementById("demo").innerHTML = "你好 " + person + "!今天过的怎么样?";
}

完整实例

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Prompt</h1>

<button onclick="myFunction()">试一试</button>

<p id="demo"></p>

<script>
function myFunction() {
  var txt;
  var person = prompt("请输入您的名字:", "哈利波特");
  if (person == null || person == "") {
    txt = "用户取消输入";
  } else {
    txt = "你好," + person + "!今天过得好吗?";
  }
  document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>

折行

如需在弹出框中显示折行,请在反斜杠后面加一个字符 n。

实例

alert("Hello\nHow are you?");

完整实例

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript</h1>

<p>在警告框中换行。</p>

<button onclick="alert('Hello\nHow are you?')">试一试</button>

</body>
</html>
相关文章
相关标签/搜索