DIV CSS 佈局教程網

JavaScript 彈窗基礎:confirm、prompt 與 window.open
編輯:關於JavaScript     

confirm():確認框

 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>confirm</title>
</head>
<body>
<script>
var con = confirm("do you like to study javascript?");
if (con) {
  document.write("I love javascript!");
} else {
  document.write("I love other lanuages!");
}
</script>
</body>
</html>

confirm 回傳布林值,因此可以直接用在 if 條件裡,讓程式依使用者的選擇分成兩條路。

prompt():輸入提示框

 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>confirm</title>
</head>
<body>
<script>
var pro = prompt("what is your name?");
document.write(pro);
</script>
</body>
</html>

prompt 回傳使用者輸入的字串;若使用者直接按確定沒填東西,得到的是空字串,按取消則是 null,實務上要分辨這兩種情況。

window.open():開啟新視窗

 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>confirm</title>
</head>
<body>
<a href="#" title="https://www.cnblogs.com/yuzheCyril/">click me</a>
<script>
var link = document.getElementsByTagName("a")[0];
link.onclick = function () {
  window.open(link.title, "blog", "width=400px,height=400px");
}
</script>
</body>
</html>

window.open 的三個參數分別是網址、視窗名稱與特徵字串。常見特徵還包括 height、scroll、status、toolbar、resizable、location 等;但要注意現代瀏覽器基於安全與體驗考量,大幅限制了可隱藏的 UI 項目,多數瀏覽器只會尊重寬高,位置與工具列往往會被忽略。

關閉視窗則是 window.close(),不過它通常只能關閉由腳本開啟的視窗,使用者手動開的分頁多數會被瀏覽器擋下。

這三個原生方法加上 window.open/close,構成了 JavaScript 最基礎的視窗互動能力,理解它們的限制,比記住語法更重要。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved