window.open和window.close的使用詳解

來源:互聯網
上載者:User

標籤:blog   class   code   c   java   tar   

有時候,我們想通過JS實現一個<a>的新開標籤的效果,此時我們想到了window.open方法實現。那麼window.open到底應該怎麼使用呢? 我們知道window.open可以新開視窗或標籤頁(這通常和瀏覽器的設定選項有關),載入指定的URL到新的或已存在的視窗中,並返回代表那個視窗的window對象。window.close可以關閉視窗,但是只能自動關閉JS開啟的視窗,如果要關閉其他視窗,必須提示使用者進行確定或取消操作(這個與瀏覽器相關,經測IE需要提示才能關閉;其他瀏覽器不允許自動關閉)。 我們可以直接使用window.open()開啟視窗,使用window.close()關閉視窗 ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 <!DOCTYPE html> <head> <meta charset="utf-8"> <title>window.open和window.close的使用詳解</title> </head> <body> <button id="openWindow">開啟視窗</button> <button id="closeWindow">關閉視窗</button> <script> (function(){  var $ = function(id) {return document.getElementById(id);}  var win = null;  //開啟視窗  $(‘openWindow‘).onclick = function() {   win = window.open();  }  //關閉視窗  $(‘closeWindow‘).onclick = function() {   win && win.close();  }  //自動關閉視窗  window.close(); })(); </script> </body> </html>

  

 window.open(URL, name[, property][,  boolean])需要四個參數:第一個參數URL:新視窗中顯示的文檔的URL,如果省略了或者為空白時,會使用‘about:blank‘第二個參數name:新視窗的名字,可以配合target使用,如果省略了,會使用‘_blank’(這裡需要簡單介紹一下:_parent和_top,_parent指的是直接父級視窗,_top指的是頂級祖先視窗)第三個參數protery:以逗號分割的選擇性參數,包含視窗大小和各種屬性。如果省略了,那麼會用預設的大小和標準的UI組件(顯式的調用更像是開啟視窗,而不是標籤)。這個參數是非標準的,HTML5規範也主張瀏覽器忽略它。第四個參數boolean:只有在第二個參數命名的是存在的視窗,才有效。聲明了由第一個參數指定的URL,替換視窗瀏覽曆史的當前條目。 window.opener指的是原始視窗,如果沒有的話,為null。 ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 <!DOCTYPE html> <head> <meta charset="utf-8"> <title>window.open和window.close的使用詳解</title> </head> <body> <button id="openWindow">開啟視窗</button> <button id="closeWindow">關閉視窗</button> <script> (function(){  var $ = function(id) {return document.getElementById(id);}  var win = null;  //開啟視窗  $(‘openWindow‘).onclick = function() {   win = window.open(‘about:blank‘, ‘_blank‘, ‘width=200,height=200‘);   //win.opener指的是新視窗原始視窗   //alert(win.opener === window);  }  //關閉視窗  $(‘closeWindow‘).onclick = function() {   win && win.close();   //主動關閉視窗後win.opener為false   //alert(win.opener === window);  }  //alert(window.opener === window);  //自動關閉視窗  //window.close(); })(); </script> </body> </html>

 

  

     

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.