我似乎无法找到一个简单的scrollTo效果。我想要做的是非常基本的,当我点击导航栏中的链接时,它必须带我到选定的div id并带有scrollTo效果。
这是我的代码。
<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 :(得分:0)
在这里使用这个jquery是小提琴http://jsfiddle.net/4qt9h95n/1/
$('a[href^="#"]').click(function() {
$('html,body').animate({ scrollTop: $(this.hash).offset().top}, 1000);
return false;
e.preventDefault();
});
答案 1 :(得分:0)
您可以使用此功能,轻松扩展到不同的点击事件。
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');
});