使用jQuery` .scroll()`移动到网站的各个部分

时间:2015-01-05 22:30:25

标签: javascript jquery animation scroll

我试图在jQuery中创建一个简单的效果,当用户向下滚动页面时,“窗格”会自动动画显示到视图中(这样用户就不必自己向下滚动)。

很难解释,所以这里是一个例子: http://jsfiddle.net/naxb22q3/1/

如您所见,当您向下滚动蓝色窗格几个像素时,会显示绿色窗格。但是,我目前拥有的代码使得一旦显示绿色窗格,您就无法再向上或向下滚动。您必须重新加载页面才能让它再次运行。

理想情况下,用户可以向上或向下滚动,动画也可以。

HTML:

<div class="pane bgBlue"></div>
<div class="pane bgGreen"></div>
<div class="pane bgRed"></div>

CSS:

.pane {
    height: 1000px;
    width: 100%;
}
.bgBlue {
    background-color: blue;
}
.bgGreen {
    background-color: green;
}
.bgRed {
    background-color: red;
}

JavaScript的:

/**
 * Lock scroll position for each pane
 * as the user scrolls down.
 */
$.fn.scrollView = function () {
    return this.each(function () {
        $('html, body').animate({
            scrollTop: $(this).offset().top
        }, 1250);
    });
}


// Variables
var windowHeight = $(window).height();
var headerHeight = $('.siteHeader').outerHeight();
var paneHeight = windowHeight - (headerHeight / 2);


// `.scroll()` function
$(window).scroll(function () {
    height = $(window).scrollTop();

    if (height > 5) {
        $('.pane.bgGreen').scrollView();

        //$(this).off('scroll');
    }


    // After we scroll past the green pane,
    // the red pane is shown (via the same animation)
    if (height > (paneHeight * 2)) {
        $('.pane.bgRed').scrollView();
    }
});

1 个答案:

答案 0 :(得分:1)

粗略的解决方案,但一个开始 - http://jsfiddle.net/bkseqsu4/

<强>使用Javascript:

&#13;
&#13;
// Variables
var windowHeight = $(window).height();
var headerHeight = $('.siteHeader').outerHeight();
var paneHeight = windowHeight - (headerHeight / 2);
var scrollLock = 0;
var paneIndex = 0;
var lastScroll = 0;
var panes = ['.pane.bgBlue', '.pane.bgGreen', '.pane.bgRed'];

/**
 * Lock scroll position for each pane
 * as the user scrolls down.
 */
$.fn.scrollView = function() {
  this.each(function() {
    $('html, body').animate({
      scrollTop: $(this).offset().top
    }, 1000, "swing", function() {
      setTimeout(function() {
        scrollLock = 0;
        var currentPosition = $(this).scrollTop();
        lastScroll = currentPosition;
      }, 100);

    });

  });
}

// `.scroll()` function
$(window).scroll(function() {

  if (scrollLock == 0) {
    var currentPosition = $(this).scrollTop();
    if (currentPosition > lastScroll) {
      paneIndex = paneIndex + 1;
    } else {
      paneIndex = paneIndex - 1;
    }

    scrollLock = 1;
    $(panes[paneIndex]).scrollView();
  }

});
&#13;
&#13;
&#13;