JavaScript 彈窗
可以在 JavaScript 中創(chuàng)建三種消息框:警告框、確認(rèn)框、提示框。
警告框
警告框經(jīng)常用于確保用戶可以得到某些信息。
當(dāng)警告框出現(xiàn)后,用戶需要點(diǎn)擊確定按鈕才能繼續(xù)進(jìn)行操作。
語(yǔ)法
window.alert() 方法可以不帶上window對(duì)象,直接使用alert()方法。
實(shí)例
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> function myFunction(){ alert("你好,我是一個(gè)警告框!"); } </script> </head> <body> <input type="button" onclick="myFunction()" value="顯示警告框" /> </body> </html>
運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例
確認(rèn)框
確認(rèn)框通常用于驗(yàn)證是否接受用戶操作。
當(dāng)確認(rèn)卡彈出時(shí),用戶可以點(diǎn)擊 "確認(rèn)" 或者 "取消" 來(lái)確定用戶操作。
當(dāng)你點(diǎn)擊 "確認(rèn)", 確認(rèn)框返回 true, 如果點(diǎn)擊 "取消", 確認(rèn)框返回 false。
語(yǔ)法
window.confirm() 方法可以不帶上window對(duì)象,直接使用confirm()方法。
實(shí)例
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> </head> <body> <p>點(diǎn)擊按鈕,顯示確認(rèn)框。</p> <button onclick="myFunction()">點(diǎn)我</button> <p id="demo"></p> <script> function myFunction(){ var x; var r=confirm("按下按鈕!"); if (r==true){ x="你按下了\"確定\"按鈕!"; } else{ x="你按下了\"取消\"按鈕!"; } document.getElementById("demo").innerHTML=x; } </script> </body> </html>
運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例
提示框
提示框經(jīng)常用于提示用戶在進(jìn)入頁(yè)面前輸入某個(gè)值。
當(dāng)提示框出現(xiàn)后,用戶需要輸入某個(gè)值,然后點(diǎn)擊確認(rèn)或取消按鈕才能繼續(xù)操縱。
如果用戶點(diǎn)擊確認(rèn),那么返回值為輸入的值。如果用戶點(diǎn)擊取消,那么返回值為 null。
語(yǔ)法
window.prompt() 方法可以不帶上window對(duì)象,直接使用prompt()方法。
實(shí)例
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> </head> <body> <p>點(diǎn)擊按鈕查看輸入的對(duì)話框。</p> <button onclick="myFunction()">點(diǎn)我</button> <p id="demo"></p> <script> function myFunction(){ var x; var person=prompt("請(qǐng)輸入你的名字","Harry Potter"); if (person!=null && person!=""){ x="你好 " + person + "! 今天感覺(jué)如何?"; document.getElementById("demo").innerHTML=x; } } </script> </body> </html>
運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例
換行
彈窗使用 反斜杠 + "n"(\n) 來(lái)設(shè)置換行。
實(shí)例
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> </head> <body> <p>點(diǎn)擊按鈕在彈窗總使用換行。</p> <button onclick="myFunction()">點(diǎn)我</button> <p id="demo"></p> <script> function myFunction(){ alert("Hello\nHow are you?"); } </script> </body> </html>
運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例