2013-08-16 83 views
2

我試圖根據用戶當前滾動的部分來修改我的導航鏈接。滾動時觸發導航

我有以下的HTML

<div class="navigation"> 
    <a href="#resume">Resume</a> 
    <a href="#design">Design</a> 
    <a href="#" class="contact">Contact</a> 
</div> 

和下面的結構

<section id="resume">my content</section> 
<section id="design">.... 

爲了實現我使用的教程中介紹here它的作品真的很好的平滑滾動的效果,但不會向我的導航鏈接添加任何類。

你能幫助理解爲什麼嗎?

非常感謝, 朱利安

+1

也許添加要使用添加代碼該班?另外,查看這個頁面,我做了同樣的事情:https://castoredc.com/nl/tour.html這是相當棘手的,但它的工作原理,雖然不完全平穩。 –

回答

0

您可以使用此:

CSS

.navigation { position:fixed; top:0; left:0; width:100%; background-color:#88f; } 
.navigation a { margin:2em; color:white; text-decoration:none; } 
.navigation a.active {text-decoration:underline; color:red;} 
#resume { margin-top:50px; } 
section { margin:2em; height:500px; background-color:#eee; } 

jQuery的

$(function(){ 
    var links = $('.navigation>a'); //.not('.contact'); 
    var sections = $('section'); 
    links.click(function(e){ 
     e.preventDefault(); 
     var p = $(this.getAttribute('href')).position().top; 
     $("html, body").stop().animate({ scrollTop: (p-30)+'px' }, 500); 
    }); 
    $(window).on('scroll', function(e){ 
     var i=0; 
     sections.each(function(j){ 
      var br = this.getBoundingClientRect(); 
      if (br.top<150) { // distance from the top of screen 
       i = j; 
      } 
     }); 
     var scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop(); 
     if (scrollBottom < 40) { // highlight the last section 
      i = sections.length-1; 
     } 
     links.removeClass('active'); 
     var active = sections.eq(i).attr('id'); 
     links.filter('[href="#'+active+'"]').addClass('active'); 
    }).trigger('scroll'); 
}); 

的jsfiddle:http://jsfiddle.net/GRcjc/3/http://jsfiddle.net/GRcjc/3/show

+0

嘿斯塔諾, 非常感謝您的幫助。 我試圖實現它,但它似乎並沒有在我的頁面上工作,但我無法弄清楚爲什麼。這裏是[鏈接](http://lookwhatjuliendid.com/projects/lwjd/)到實際頁面。你介意快點看看,我想這只是一些小事。 (請注意,「#導航」僅在<900px)頁中顯示。再次感謝! – user2689717

+0

你好,你使用的是舊的jQuery1.6,所以在你的控制檯出現消息'TypeError:$(...)。on不是一個函數',要麼改變'$(window).on('scroll ',function(e){'to'$(window).scroll(function(e){'或者使用更新的jQuery [1.7+](http://api.jquery.com/on/)) – Stano

+0

再次感謝。我已經更新到1.7,錯誤似乎消失了,但它仍然不起作用......它可能與腳本的位置有關嗎? – user2689717

0

怎麼樣的一個插件,以儘量減少你的工作? http://scrollnav.com/ =)

+0

這不是他的問題的答案,他已經實現了一些東西,需要幫助才能使其工作。 –

+0

嘿伊戈爾。謝謝你的提示。 我的導航僅限於手機和平板電腦+只有2個鏈接我希望我能找到一個簡單的方法來做到這一點,這個模板似乎是一個很好的解決方案... – user2689717