jQuery窗口进入/离开视图处理程序

时间:2018-10-11 19:18:22

标签: javascript jquery

一旦动画消失,我想在HTML页面上停止动画

我尝试使用

$(window).focus(function () {
    // start animation
}).blur(function () {
    // stop animation
});

但是如果这段代码是另一个窗口的背景,则此代码也会停止动画。

在JS或jQuery中是否有用于窗口进入/离开视图的处理程序?

即像这样:

$(window).windowInView(function () {
    // start animation
}).windowOutView(function () {
    // stop animation
});

1 个答案:

答案 0 :(得分:1)

有两种方法: window.requestAnimationFrame()

从链接页面获取/修改的示例

<div id="rec" style="width: 5px; height: 5px; background: black;"></div>

var start = null;
var left=false;
var element = document.getElementById('rec');
element.style.position = 'absolute';

function step(timestamp) {
  if (!start) start = timestamp;
  if(!left){
      var progress = timestamp - start;
      element.style.left = Math.min(progress / 10, 600) + 'px';
      if (progress < 6000) {
        window.requestAnimationFrame(step);
      }else{
        start = timestamp;
        left = true;
        window.requestAnimationFrame(step);
    }
  }else{
     var progress = (start+6000)-timestamp;
      element.style.left = Math.max(progress / 10, 0) + 'px';
     if (progress > 0) {
        window.requestAnimationFrame(step);
     }else{
        start = timestamp;
        left=false;
        window.requestAnimationFrame(step);
     }
  }
}

Page Visibility API

document.addEventListener("visibilitychange", function(){
    if (document.hidden) {
        console.log('hidden');
    }else{
        console.log('visible');
    }}, false);