Set anchor as active with jquery

北城余情 提交于 2019-12-24 11:04:07

问题


i have short question.. i got 3 content boxes and all have a menu with anchor-links to the content-boxes below! when i visit the site the first anchor is set ti active.. when i click now on no.2 in headline 1 it jumps to the 2nd anchor.. but the problem is i have to scroll a little bit above with the mousewheel to set the 2nd anchor as active.

and backwards too. when i click on box3 at anchor1..

any ideas to solve the problem?

WHEN SCROLLING UP AND DOWN IT WORKS PERFECT! JUST THE JUMP OVER THE ANCHOR MADE PROBLEMS

here is the demo: http://jsfiddle.net/wv9EQ/

here is the javascript code:

$(function(){
    var sections = {},
        _height  = $(window).height(),
        i        = 0;

    //// Grab positions of our sections
    $('.section').each(function(){
        sections[this.name] = $(this).offset().top;
    });

    $(document).scroll(function(){
        var $this = $(this),
            pos   = $this.scrollTop();

        for(i in sections){
            if(sections[i] > pos && sections[i] < pos + _height){
                $('a').removeClass('active');
                $('.nav_' + i).addClass('active');
            }  
        }
    });
});

EDIT: i can't add active to all links! i include this small navi as php and its dynamic for all boxes! when i set all to active than are all anchors active :D


回答1:


Just do the same sort of thing when a link is clicked:

$('.head-nav-button').click(function()
{
    $('a').removeClass('active');
    $('.nav_' + $(this).attr('href').replace('#', '')).addClass('active');
});

http://jsfiddle.net/wv9EQ/7/




回答2:


for your code use the simple way

http://jsfiddle.net/wv9EQ/4/

  <li><a href="#2-SP" class="head-nav-button nav_2-SP active">2. SP.</a></li>



回答3:


Remove this

for(i in sections){
        if(sections[i] > pos && sections[i] < pos + _height){
            $('a').removeClass('active');
            $('.nav_' + i).addClass('active');
        }  
    }

And just add the "active" class where you need it like here http://jsfiddle.net/wv9EQ/6/



来源:https://stackoverflow.com/questions/13306545/set-anchor-as-active-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!