使用onclick事件关闭JavaScript窗口

Closing a JavaScript window with an onclick event

本文关键字:JavaScript 窗口 onclick 事件 使用      更新时间:2023-11-20

我们必须制作一个打开新窗口的JavaScript,然后您需要能够在窗口内点击再次关闭它。但我的代码不起作用,有人能给我一个最好的答案吗?

function swipe() {
   var largeImage = document.getElementById('largeImage');
   var url = largeImage.getAttribute('src');
   var w = largeImage.naturalWidth;
   var h = largeImage.naturalHeight;   
   window.open(url,"Image", "height="+ h +", width="+ w +", resizable=yes");
   var myWindow = window.self;
   myWindow.addEventListener("click", clickHandler);
   var elementIsClicked = false;
   function clickHandler(){ 
    elementIsClicked = true
   }
   function isElementClicked (){
    if(elementIsClicked){
            newWindow.close();
    }
   }
   setInterval(isElementClicked, 500);

}

一条注释说newWindow在任何地方都没有定义。我想你是想用myWindow对象。myWindow.close()将工作,因为它会关闭窗口。

如果你想在第一次加载时执行这个,你应该把它放在window.onload函数或自调用函数中。此外,为了在所有浏览器中实现完全兼容性,您应该省略resizable=yes部分,因为只有IE支持它。

此外,如果要使用jQuery,可以在$(window).load()函数中执行此方法。

您可以使用document.write()

window.onload = function() {
   var largeImage = document.getElementById("largeImage");
   // var url = largeImage.getAttribute('src');
   var w = largeImage.naturalWidth;
   var h = largeImage.naturalHeight; 
   // open blank `window`
   var popup = window.open("", "Image"
                          , "height="+ h 
                            +", width="+ w 
                            +", resizable=yes");
   // write `img` `outerHTML` to `popup` `window`
   popup.document.write(largeImage.outerHTML);
   window.onclick = function() {
     // close `popup`
     popup.document.write("<script>this.close()<'/script>");
     // remove `onclick` handler
     this.onclick = null;
   }
}

plnkrhttp://plnkr.co/edit/0KUPw3UlEF0ONO1vDoOU?p=preview

var newWindow;
function windowOpener() {
  var url = "http://stackoverflow.com/questions/36387144/closing-a-javascript-window-with-an-onclick-event";
  newWindow = window.open(url, "Popup", "width=700,height=500");
  var timer = setInterval(function() {
    if (newWindow.closed) {
      alert("window closed");
      clearInterval(timer);
    }
  }, 250)
}
<button onclick="windowOpener();">Open a window</button>

这是打开和检测它何时关闭的代码。

这是codepen.io上的示例代码http://codepen.io/sujeetkrjaiswal/pen/vGebqy

由于某种原因,代码没有在stackoverflow中运行,请在codepen上尝试。

感谢大家的回答。以下是我的问题的解决方案:

  function swipe() {
   var largeImage = document.getElementById('largeImage');
   var url = largeImage.getAttribute('src');
   var w = largeImage.naturalWidth;
   var h = largeImage.naturalHeight; 
   var popup = window.open(url,"Image", "height="+ h +", width="+ w +", resizable=yes");

   popup.document.write('<img src="women_running_small.jpg" id="largeImage" style="width:95% ;height:95%; object-fit:contain"/>');
   popup.onclick = function() {
     // close `popup`
     popup.document.write("<script>this.close()<'/script>");
     // remove `onclick` handler
     this.onclick = null;
   }

}