2014-12-05 35 views
0

我似乎無法找到一個簡單的scrollTo效果。我想要做的是非常基本的,就是當我點擊導航欄中的鏈接時,它必須帶着我到選定的div id以scrollTo效果。ScrollTo效果(href對div)

這是我的代碼。

<nav> 
<ul> 
<li><a href="#home">Home</a></li> 
<li><a href="#about">About</a></li> 
<li><a href="#contact">Contact</a></li> 
</ul> 
</nav> 

<section id="home"> 
    CONTENT 
</section> 

<section id="about"> 
    CONTENT 
</section> 

<section id="contact"> 
    CONTENT 
</section> 

JS:

<!----- Navegación Slide ---> 
$(document).ready(function() { 
  $('a[href*=#]').each(function() { 
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
    && location.hostname == this.hostname 
    && this.hash.replace(/#/,'')) { 
      var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']'); 
      var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false; 
       if ($target) { 
         var targetOffset = $target.offset().top; 

<!----- Funcion click + scroll al #div---> 
         $(this).click(function() { 
      $("nav ul li a").removeClass("active"); 
      $(this).addClass('active'); 
           $('html, body').animate({scrollTop: targetOffset}, 1000); 
           return false; 
         }); 
      } 
    } 
  }); 

}); 

這似乎是工作,但它不帶我去,選擇部分的頂部。它需要喜歡該部分內容的中間部分。

+0

編輯,忘了把它放進去。 – Mark 2014-12-05 18:19:55

+0

一定是愚蠢的 – Mark 2014-12-05 18:31:46

+0

標題改變了,更準確。 – 2014-12-06 14:01:42

回答

0

這裏使用這個jQuery是小提琴http://jsfiddle.net/4qt9h95n/1/

$('a[href^="#"]').click(function() { 
    $('html,body').animate({ scrollTop: $(this.hash).offset().top}, 1000); 
    return false; 
    e.preventDefault(); 
}); 
0

您可以使用此功能,它很容易expandaple不同的單擊事件。

function transitionTo(elem){ 

    $('html, body').stop().animate({scrollTop: $(elem).offset().top 

    }, 2000, function() { 


    }); 
} 

// and call it with:  

$('#link').on('click', function(e){ 
    e.preventDefault(); 

    transitionTo('#div'); 

    });