我该如何计算一个窗口打开的秒数?

3

我正在尝试编写一个脚本,其中需要一个计时器来计算弹出窗口打开的秒数。虽然我是编程新手,但我想应该使用JavaScript吧?

2个回答

5

在弹出窗口中,您可以使用window对象的unload事件来检测窗口关闭或导航到新页面,之前在文档顶部记录打开时间。例如:

<html>
  <head>
    <script type="text/javascript">
      var start = new Date();

      window.onunload = function() {
        var end = new Date();
        var secondsOpen = Math.floor((end - start) / 1000);
        alert("Pop-up was open for " + secondsOpen + " seconds");
      };
    </script>
  </head>
  <body>
     ...
  </body>
</html>

1

当涉及到计算某个时间段时,我总是使用日期对象,在弹出窗口打开时将新日期存储在变量中,并将该值减去当前日期。以下是一个示例:

// Execute this when the popup opens
var popup_opened = (new Date()).getTime();

// And this way you can get the time (in seconds) that the popup has been opened
var current_time = (new Date()).getTime();
var time_spent_opened = (current_time - popup_opened)/100;

你也可以使用一个函数来获取弹出窗口已经打开的时间:

function getPopupTime() {
    var current_time = (new Date()).getTime();
    return (current_time - popup_opened)/100;
}

那我不应该检查弹出窗口是否已关闭吗?或者更好的方法是什么? - user586025

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接