滚动功能不应滚动到顶部

时间:2014-02-04 06:22:53

标签: jquery scroll

我在我的onepage上有这个脚本,它运行正常。但我需要脚本无法滚动到第一类部分。

这可能吗?

$(document).ready(function () {
var divs = $('.section');
var dir = 'up'; // wheel scroll direction
var div = 0; // current div
$(document.body).on('DOMMouseScroll mousewheel', function (e) {
    if (e.originalEvent.detail > 0 || e.originalEvent.wheelDelta < 0) {
        dir = 'down';
    } else {
        dir = 'up';
    }
    // find currently visible div :
    div = -1;
    divs.each(function(i){
        if (div<0 && ($(this).offset().top >= $(window).scrollTop())) {
            div = i;
        }
    });
    if (dir == 'up' && div > 0) {
        div--;
    }
    if (dir == 'down' && div < divs.length) {
        div++;
    }
    //console.log(div, dir, divs.length);
    $('html,body').stop().animate({
        scrollTop: divs.eq(div).offset().top
    }, 1300);
    return false;
});
$(window).resize(function () {
    $('html,body').scrollTop(divs.eq(div).offset().top);
});

});

2 个答案:

答案 0 :(得分:0)

您可以在jquery中使用:first选择器。

例如

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>first demo</title>
  <style>
  td {
    color: blue;
    font-weight: bold;
  }
  </style>
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<table>
  <tr class='nn'><td>Row 1</td></tr>
  <tr class='nn'><td>Row 2</td></tr>
  <tr class='nn'><td>Row 3</td></tr>
</table>

<script>
$( ".nn:first" ).css( "font-style", "italic" );
</script>

</body>
</html

More about :first

答案 1 :(得分:0)

也许你可以使用这个方便的inview plugin来简化代码吗?

这是另一种接近它的方法:

<强> HTML

<div class="page green">
    page 1
</div>
<div class="page orange">
    page 2
</div>
<div class="page blue">
    page 3
</div>

<强> JS

// caching
var $body = $("body");
var $window = $("window");
var activeSectionOffset = 0; // value to scroll to used by the resize event
var resizeTimeout = null; // to throttle resize events

// animating to next visible element
$(".page").on("inview", function (event, visible, topOrBottomOrBoth) {
  if (visible == true) {
     var scrollVal = $(this).addClass("active").offset().top; // the active class isnt really needed
     activeSectionOffset = scrollVal;
     animateScrollTo( scrollVal );
  } else {
     $(this).removeClass("active");
  }
});

// handy function that scrolls body element to the scrollVal provide
function animateScrollTo( scrollVal ) {
    $body.stop().animate({
        scrollTop: scrollVal
    }, 200);   
}

// resize event
$window.on("resize", function() {
    resizeTimeout = setTimeout(function() { // suppressing multiple resize events
        clearTimeout( resizeTimeout );
        animateScrollTo( activeSectionOffset );
    }, 300);
}).trigger("resize");

小提琴:http://jsfiddle.net/Varinder/cGLwJ/3/