当用户在页面上时触发事件

Jos*_*ose 5 html javascript jquery

我有这个代码

$(document).ready(function(){
    var fade_in = function(){
        $(".quote").fadeIn();
    }
    setTimeout(fade_in, 2000);
    var fade_out = function() {
      $(".quote").fadeOut();
    }
    setTimeout(fade_out, 10000);
});
Run Code Online (Sandbox Code Playgroud)

它的作用是div"引用"慢慢淡入,停留几秒然后淡出.我想要的是所有这一切都发生在用户在页面上,如果你不在页面中,文本淡入淡出,淡出而你错过它.我怎样才能做到这一点?

Kis*_*man 2

有两种方法

第一:(有点旧)

$(document).ready(function() {
  window.onfocus = function() {
    var fade_in = function() {
      $(".quote").fadeIn();
    }
    setTimeout(fade_in, 2000);
    var fade_out = function() {
      $(".quote").fadeOut();
    }
    setTimeout(fade_out, 10000);
  };
});
Run Code Online (Sandbox Code Playgroud)
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="quote">quote</div>
Run Code Online (Sandbox Code Playgroud)

第二 :

function getHiddenProp() {
  var prefixes = ['webkit', 'moz', 'ms', 'o'];

  // if 'hidden' is natively supported just return it
  if ('hidden' in document) return 'hidden';

  // otherwise loop over all the known prefixes until we find one
  for (var i = 0; i < prefixes.length; i++) {
    if ((prefixes[i] + 'Hidden') in document)
      return prefixes[i] + 'Hidden';
  }

  // otherwise it's not supported
  return null;
}

function isHidden() {
  var prop = getHiddenProp();
  if (!prop) return false;

  return document[prop];
}

// use the property name to generate the prefixed event name
var visProp = getHiddenProp();
if (visProp) {
  var evtname = visProp.replace(/[H|h]idden/, '') + 'visibilitychange';
  document.addEventListener(evtname, visChange);
}

function visChange() {
  var txtFld = document.getElementById('visChangeText');

  if (txtFld) {
    if (!isHidden()) {
      var fade_in = function() {
        $(".quote").fadeIn();
      }
      setTimeout(fade_in, 2000);
      var fade_out = function() {
        $(".quote").fadeOut();
      }
      setTimeout(fade_out, 10000);

    };
  }
}
}
Run Code Online (Sandbox Code Playgroud)
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

 <div class="quote">quote</div>
Run Code Online (Sandbox Code Playgroud)