javascript - jQuery 窗口进入/退出 View 处理程序

标签 javascript jquery

我想在 HTML 页面离开 View 后停止动画

我尝试使用

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

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

JS 或 jQuery 中是否有用于窗口进入/退出 View 的处理程序?

即像这样:

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

最佳答案

有两种方法: 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);

关于javascript - jQuery 窗口进入/退出 View 处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52767435/

相关文章:

jquery - 用jQuery动画显示ckeditor

javascript - 使用 CSS 打印页面的不同部分

javascript - 将迭代中的值传递给函数参数

javascript - 避免 ng-model 上的 Angular 重复

javascript - jQuery 日期选择器功能

javascript - backbone.js 在 render() 中触发事件

javascript - Jquery 在 .hover() 上显示和隐藏 div

javascript - 如何根据不同的键对数组进行排序

javascript - 判断元素是否存在

javascript - Drupal 仪表板中的问题