javascript - 关闭选项卡时忽略可见性变化

标签 javascript html

应该什么条件才能在切换选项卡时调用 d.fx.pause(); ,而不是在关闭选项卡时调用(因为在我的情况下它是无用的)。

window.addEventListener("beforeunload", function() {
    /* NOT USED */
    console.log("1: beforeunload, could ask for confirmation", document.hidden);
});

document.addEventListener("visibilitychange", function() {
    /* pause when switching away, but not when unloading */
    const condition = true; // ?
    console.log("2: visibilitychange", document.hidden);
    if (document.hidden && condition) {
      //d.fx.pause();
    }
});

window.addEventListener("unload", function() {
    console.log("3: unload", document.hidden);
});

最佳答案

您可以在 beforeunload 事件中添加一个标志,并在 visibilitychange 中检查该标志。

例如

var unloading = false;
window.addEventListener("beforeunload", function() {
  unloading = true;
  /* NOT USED */
  console.log("1: beforeunload, could ask for confirmation", document.hidden);
});

document.addEventListener("visibilitychange", function() {
  /* pause when switching away, but not when unloading */
  const condition = true; // ?
  console.log("2: visibilitychange", document.hidden);
  if (!unloading && document.hidden && condition) {
    //d.fx.pause();
    console.log("d.fx.pause()");
  }
});

window.addEventListener("unload", function() {
  console.log("3: unload", document.hidden);
});

关于javascript - 关闭选项卡时忽略可见性变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46577684/

相关文章:

html - 即使应用了 reset.css,不同浏览器的输出也不同

javascript - 如何对div值求和?

javascript - 如何沿着图像移动几何图形?

javascript - jQuery-Ajax 创建的 Checkboxlist 不响应点击

javascript - 尝试使用 html 按钮更改变量的值,但出了点问题?

Javascript 如果 cookie 存在则应用 css

javascript - 如何通过 Drupal 8 模块使用 jQuery 代码?

javascript - 'keypress' 的 addeventlistener = 验证码替代方案?

Javascript 函数参数在花括号中

php - 从 HTML 调用 PHP 的问题