jquery autoscroll从顶部偏移

时间:2013-06-10 16:00:39

标签: jquery offset autoscroll

我想以这种方式设置“autoscroll to class”jquery脚本,因此它显示了偏离窗口顶部的目标类像素。这个插件有可能吗?

jsfiddle:http://jsfiddle.net/dzorz/cybMJ/

HTML:

<div id="nav-dock"> 
<a id="prev" href="#">&uarr; Prev</a> 
    <a id="next" href="#">&darr; Next</a>
 </div>
 <br><br><br><br><br><br><br><br><br><br>
 <br><br><br><br><br><br><br><br><br><br>
 <div class=text>
<b>First</b>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
  In iaculis augue sapien, in facilisis lorem ullamcorper eu. 
 Nunc at nulla metus. Pellentesque posuere quam id 
 nunc <span class="highlight1">posuere</span> sagittis. Vivamus varius 
 euismod nisi, ac condimentum mauris aliquam vitae. Ut faucibus eros vitae 
 pharetra eleifend. Pellentesque volutpat facilisis porttitor. Nullam in 
 turpis a nulla placerat placerat.    
 </div>
 <br><br><br><br><br><br><br><br><br><br>
 <div class=text>
<b>Second</b>
Cras semper purus sit amet euismod molestie. Vivamus dapibus hendrerit elit 
 eget tristique. Ut pulvinar adipiscing magna, eget viverra risus sollicitudin et.
  Morbi odio lacus, malesuada vel dapibus vitae, blandit ut metus.
 Vivamus cursus fringilla <span class="highlight1">felis</span> id facilisis.   
 </div>
 <br><br><br><br><br><br><br><br><br><br>
 <div class=text>
<b>Third</b>
Aliquam et mattis mi. Mauris vel sagittis orci, id tempor neque. 
 Aenean at arcu eu quam suscipit fermentum. Sed tempor, urna in malesuada 
 sollicitudin, nulla erat <span class="highlight1">malesuada</span> ligula, 
 sed  ultricies ipsum dui a dui. Ut at sem quis lectus aliquet vulputate.     
 </div>
 <br><br><br><br><br><br><br><br><br><br>
 <div class=text>
<b>Fifth</b>
Praesent sagittis tortor a purus euismod ultrices eu vitae est. 
 Vivamus a facilisis dolor. Donec id tincidunt erat. Fusce elementum imperdiet 
 augue, at pretium lectus <span class="highlight1">dictum</span> sit amet. 
 Nullam pharetra dui arcu, ut tempus nulla interdum non. Etiam et mattis augue.    
 </div>

脚本:

$(function() {

function scroll(direction) {

    var scroll, i,
            positions = [],
            here = $(window).scrollTop(),
            collection = $('.highlight1');

    collection.each(function() {
        positions.push(parseInt($(this).offset()['top'],10));
    });

    for(i = 0; i < positions.length; i++) {
        if (direction == 'next' && positions[i] > here) { scroll = collection.get(i); break; }
        if (direction == 'prev' && i > 0 && positions[i] >= here) { scroll = collection.get(i-1); break; }
    }

    if (scroll) {
        $.scrollTo(scroll, {
            duration: 750       
        });
    }

    return false;
}

$("#next,#prev").click(function() {        
    return scroll($(this).attr('id'));        
}).triggerHandler('click');

$(function() {

function scroll(direction) {

    var scroll, i,
            positions = [],
            here = $(window).scrollTop(),
            collection = $('.highlight1');

    collection.each(function() {
        positions.push(parseInt($(this).offset()['top'],10));
    });

    for(i = 0; i < positions.length; i++) {
        if (direction == 'next' && positions[i] > here) { scroll = collection.get(i); break; }
        if (direction == 'prev' && i > 0 && positions[i] >= here) { scroll = collection.get(i-1); break; }
    }

    if (scroll) {
        $.scrollTo(scroll, {
            duration: 750       
        });
    }

    return false;
}

$("#next,#prev").click(function() {        
    return scroll($(this).attr('id'));        
}).triggerHandler('click');

});

您可以自由更新我的jsfiddle。

1 个答案:

答案 0 :(得分:1)

好的,我为你重写了一些东西,然后将所有活动部分完全展开,将它们分解。虽然,随着评论的消失,你会发现这个代码比你自己的代码短得多!

Example with comments

//  the following establishes your own namespace, place everything about the scroll function in this namespace
var hlScroll = {
    //  properties
    buffer: 50, //  pixel buffer, positive is px above element, negative would move it so many pix below
    speed: 500, //  scroll speed, 1000 = 1second
    //  method
    scrollTo: function(e) {
        var gotoEle;    //  will be the element to find "top" too
        switch ($(this).attr('id')) {   //  same as an if else, but more visually sound on 2 strings in question
            case "next":    //  obviously go to next element
                //  filter is jquery function that allows us to get only certain elements in a collection
                //  here, our collection is ALL elements having class "highlight1"
                //  the filter method is kind of like .each, it goes through each element, the i means "index"
                //  in order for an element to stay in the collection, it must return true
                //  in this case, looking for "next", I see if current element's top is higher than window top + our buffer
                //  by including the buffer, I can make suer not to skip an element that might be "close" to the buffer but not over
                gotoEle = $('.highlight1').filter(function(i) { return $(this).offset().top > ($(window).scrollTop() + hlScroll.buffer) }).first();
                //  since we are getting next, we only want the first element returned, thus `.first()` will return just that!
                break;
            case "prev":
                //  a lil dif from above, here we look for the last element who's top is higher than the window
                gotoEle = $('.highlight1').filter(function(i) { return $(this).offset().top < $(window).scrollTop() }).last();
                break;
        }
        //  the if statement here keeps the scroll from firing if no element found
        //  if the element is found, we animate the page to scroll the element previously selected, - the buffer, keeping it so many pixels above the element (unless the buffer is negative)
        if (gotoEle.length) $("html, body").animate({ scrollTop: gotoEle.offset().top - hlScroll.buffer  }, hlScroll.speed);
        //  notice i selected "html, body". these are our main page elements which hold the page scroll
        //  you could adjust this in the future to scroll a parent container instead!
    }
}

$(function() {
    $("#next, #prev").on("click", hlScroll.scrollTo).click();
});

Example without comments

var hlScroll = {
    buffer: 50,
    speed: 500,
    scrollTo: function(e) {
        var gotoEle;
        switch ($(this).attr('id')) {
            case "next":
                gotoEle = $('.highlight1').filter(function(i) { return $(this).offset().top > ($(window).scrollTop() + hlScroll.buffer) }).first();
                break;
            case "prev":
                gotoEle = $('.highlight1').filter(function(i) { return $(this).offset().top < $(window).scrollTop() }).last();
                break;
        }
        if (gotoEle.length) $("html, body").animate({ scrollTop: gotoEle.offset().top - hlScroll.buffer  }, hlScroll.speed);
    }
}

$(function() {
    $("#next, #prev").on("click", hlScroll.scrollTo).click();
});

进一步阅读: