如何使经典的jQuery视差更加流畅

时间:2017-11-27 12:06:44

标签: javascript jquery css parallax

我有一个像这样的经典jQuery视差设置

$(window).scroll(function () {
  parallax();
});

var offset;

$(document).ready(function(){
  var p = $( ".content" );
  var offset = p.offset();
  var offset = offset.top;
});

function parallax() {
  render($(document).scrollTop());
}

function render(ev) {
  var t = ev;
  var y = Math.round(t * .25);
  $('.content').css('bottom', - y - 100 + 'px');
}

有没有办法让它更流畅?

1 个答案:

答案 0 :(得分:1)

您可能想尝试在transition元素上添加.content

.content{
  transition: bottom 0.3s linear;
}

您需要以与转换时指定的间隔相同的间隔触发视差功能。

尝试使用类似的方法以相同的间隔启动视差功能:

var interval;
var timeout;

$(window).scroll(function(event){
  //prevent from stopping the interval
  clearTimeout(timeout);

  //execute parallax every 300ms => same as transition
  if(!interval){
    parallax();
    interval = setInterval(function(){
      parallax();
    }, 300);
  }

  //stops the interval after you stopped scrolling for x amount of time
  timeout = setTimeout(function(){
    clearInterval(interval);
    interval = null;
  }, 300);
});