Вопрос

I've been playing around with Bootstrap a lot lately and I'm currently in the process of creating a new template for my website. I've done a lot of searching on this issue, but most of the things I find are for people that can't get scrollspy to work at all.

What I'd like to do is create a side-navigation that has a separate target for each letter of the alphabet. You click on a link to bring you to that section of the content panel. The content panel will be an alphabetized list of whatever. Manually scrolling the page should automatically set the links in the navbar to active, causing the letters to highlight (or whatever I decide to do with them via CSS).

For those of you who are familiar with the iPhone, it is much like what they have implemented when viewing organized lists such as the Contacts app. Let's say that the viewport shows several alphabetized names, starting from D at the top of the viewport, and H at the bottom.

With scrollspy, only the closest target is being highlighted. The example below shows what I mean.

Example: http://jsfiddle.net/panchroma/ExWDq/embedded/result/

I hope that I've been specific enough for you to understand what I am trying to do. Let me know if I've lost you anywhere and I'll try and re-explain a bit better.

Is scrollspy the tool to use to accomplish this task?

If I knew of a way to check if an element is visible on screen, I might be able to utilize that to make something in Javascript that could accomplish everything I need, but I was hoping to be able to use scrollspy for this.

Thanks for reading. :)

Это было полезно?

Решение

I'm not familiar with scrollspy, but the functionality you're after isn't that complex:

Adapting the function provided here this should give you a list of which elements in a set are currently visible. You can apply/remove whatever CSS classes you want given this information.

You can run this handler on the 'scroll' event in the browser, though you might want to 'throttle' or 'debounce' it. I believe there are jQuery plugins that provide the equivalent, but each of those is only a dozen lines of code or so.

function getVisible( $els ) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    return $els.filter(function(i, elem) {
        var elemTop = $(elem).offset().top;
        var elemBottom = elemTop + $(elem).height();

        // Fully or partially visible, pick one

        // element is _fully_ visible
        return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));

        // element is _partially_ visible
        return ((elemBottom <= docViewBottom) || (elemTop >= docViewTop));
    });
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top