2015-03-11 2 views
0

У меня простая навигация.jquery get .offset значение переменной (элемента), затем анимировать его

<nav> 
    <a href="#section1">page 1</a> 
    <a href="#section2">page 2</a> 
    <a href="#section3">page 3</a> 
</nav> 

Когда пользователь нажимает на одну из ссылок, я хочу страницу, чтобы оживить в соответствующий раздел на странице.

Я не могу получить значение .offset(). Верхнее значение от переменной. Любая помощь будет принята с благодарностью.

$("nav a").click(function(e) { 
    e.preventDefault(); 
    // figure out which button was clicked 
    var targetName = $(this).attr("href"); 
    // get the current position of the target element 
    var targetOffset = targetName.offset().top; 
    // send the page there 
    $("html, body").animate({ 
     top: targetOffset 
    }); 
}); 

ответ

1

Проблема заключается в том targetName не JQuery объекта, на вашей консоли вы должны увидеть ошибку, например Uncaught TypeError: undefined is not a function

$("nav a").click(function(e) { 
    e.preventDefault(); 
    // figure out which button was clicked 
    var targetName = $(this).attr("href"); 
    // get the current position of the target element 
    var targetOffset = $(targetName).offset().top; //targetName is not jQuery object 
    // send the page there 
    $("html, body").animate({ 
     scrollTop: targetOffset //also use scrollTop to animate scrolling 
    }); 
}); 

Демонстрация: Fiddle

+0

Thanks Arun! Отлично! – afthole

0

Вы должны установить надлежащий объект для анимации, чтобы понравиться Arun говорит, я был неправ - не ясно думать :)

$("nav a").click(function(e) { 
     e.preventDefault(); 
     // figure out which button was clicked 
     var targetName = $(this).attr("href"); 
     // get the current position of the target element 
     var targetOffset = $(targetName).offset().top; 
     // send the page there 
     $("html, body").animate({ 
      scrollTop: targetOffset 
     }, 1400); 
    }); 

пример JSFIDDLE