2013-09-07 2 views
1

Я хочу поэкспериментировать с особенностью ive, найденной на довольно классном сайте, но я не знаю, с чего начать.JQuery Подчеркивание на прокрутке

http://adamrudzki.com/

Функция является подчеркивание элемент, который перемещается поперек как страница прокручивается вниз. Я нашел аналогичный SO здесь Underlining menu item, но если кто-то может помочь с функциональностью im после id, то оцените его. Не слишком хорошо знакомы с JQuery.

Заранее благодарен!

+0

Я проверил ваш профиль раньше и нашел это без ответа, см. Мой ответ ниже. ура! –

ответ

3

На вашем примере сайта каждый <a> тег имеет элемент <span>, который служит в качестве подчеркивания. Но я думаю, что мы можем отрезать разметку и вместо этого использовать border-bottom. В принципе, здесь есть два события: scroll() и click().

Это основная разметка:

<nav> 
    <a>Home</a> 
    <a>About</a> 
    <a>Portfolio</a> 
    <a>Contact</a> 
</nav> 
<div id="contents"> 
    <section>Home</section> 
    <section>About</section> 
    <section>Portfolio</section> 
    <section>Contact</section> 
</div> 

CSS, просто хотел бы подчеркнуть границы:

a { 
border:0 solid #FFF; 
border-bottom-width:0; 
} 

JQuery scroll() событие:

$(window).scroll(function() { 
    //get the window scrollTop on scroll 
    var st = $(window).scrollTop(); 
    /* we use each() to iterate on every section and 
     check if the offset position is in relative condition to the 
     scrollTop value 
    */ 
    $('#contents section').each(function (index) { 
     var offsetTop = $(this).offset().top, 
      h = $(this).height(); 
     //this condition satisfies that this section is currently on the viewport 
     if (st >= offsetTop && st < offsetTop + h) { 
      /*find the nav <a> that has the same index to this section 
      currently on the viewport and 
      show its border-bottom by setting its width. 
      */ 
      $('nav a').eq(index).css({ 
       'border-bottom-width': '3px' 
      }); 
     } else { 
      //hide the border-bottom 
      $('nav a').eq(index).css({ 
       'border-bottom-width': '0' 
      }); 
     } 
    }); 
}).trigger('scroll'); 

нав <a>click() событие:

$('nav a').click(function() { 
    /* click has no index argument compared to each() function 
    so we have to get it with index() */ 
    var index = $(this).index(), 
     $target = $('#contents section').eq(index); // find the target section 
    //animate scrolling to the target section 
    $('html, body').stop(true, true).animate({ 
     scrollTop: $target.offset().top 
    }, 'slow'); 
}); 

Обратите внимание, что мы используем index целевые точную <section>/<a>, это решение будет работать должным образом, если <section> расположен соответственно Nav <a> позицию расположения.

См. Этот образец jsfiddle.

+0

Вы, сэр, легендарны. – webbist

Смежные вопросы