移动端 监听滚动事件 且 监听惯性

  var timer = null;
var timer1 = null;
window.addEventListener('touchstart',function(e){
  var scrollTop  = document.documentElement.scrollTop || document.body.scrollTop;
  var containerH = $('img').height(); // 图片的高度
  if (scrollTop>=0 && scrollTop < containerH) {
    var bag = scrollTop / containerH;
    $('header').css('background','rgba(0,173,176,'+ bag +')');
  }
},false);

window.addEventListener('touchmove',function(e){
  clearInterval(timer1);
  var scrollTop  = document.documentElement.scrollTop || document.body.scrollTop;
  var containerH = $('img').height(); // 图片的高度
  if (scrollTop>=0 && scrollTop < containerH) {
    var bag = scrollTop / containerH;
    $('header').css('background','rgba(0,173,176,'+ bag +')');
  }
},false);

window.addEventListener('touchend',function(e){
  clearTimeout(timer);
  timer = setTimeout(function() {
    var scrollTop  = document.documentElement.scrollTop || document.body.scrollTop;
    var containerH = $('img').height(); // 图片的高度
    if (scrollTop>=0 && scrollTop < containerH) {
      var bag = scrollTop / containerH;
      $('header').css('background','rgba(0,173,176,'+ bag +')');
    }
    if (scrollTop < 200) {
      timer1 = setInterval(function() {
        if (scrollTop < 0) {
          $('header').css('background','rgba(0,173,176,'+ 0 +')');
          clearInterval(timer1);
          return;
        }
        scrollTop -= 200;
        console.log(scrollTop);
        document.body.scrollTop = document.documentElement.scrollTop = scrollTop;
      }, 100)
    }
  }, 100)
},true);

 

你可能感兴趣的:(js代码)