jQuery 单击菜单中的“关于”或“联系”后如何滚动到 div?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14524297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to scroll to div after click on About or Contact in my menu?
提问by vavelde
How to scroll to div (e.g: #about, #contact) after click on About or Contact in my menu?
单击菜单中的“关于”或“联系人”后,如何滚动到 div(例如:#about、#contact)?
<div class="masthead">
<ul class="nav nav-pills pull-right">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
<h3 class="muted">Name site</h3>
</div>
回答by JohnJohnGa
Your html:
你的html:
<div class="masthead">
<ul class="nav nav-pills pull-right">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
<h3 class="muted">Name site</h3>
</div>
<div id="about">about</div>
<div id="contact">contact</div>
Your javascript:
你的javascript:
$('ul.nav').find('a').click(function(){
var $href = $(this).attr('href');
var $anchor = $('#'+$href).offset();
window.scrollTo($anchor.left,$anchor.top);
return false;
});
If you want to use animate, replace
如果要使用动画,请替换
window.scrollTo($anchor.left,$anchor.top);
by
经过
$('body').animate({ scrollTop: $anchor.top });
回答by Eli Gassert
It is easier than you think.
这比你想象的要容易。
<div class="masthead">
<ul class="nav nav-pills pull-right">
<li class="active"><a href="#">Home</a></li>
<li><a href="#About">About</a></li>
<li><a href="#Contact">Contact</a></li>
</ul>
<h3 class="muted">Name site</h3>
</div>
<div id="About">Here's my about</div>
...
<div id="Contact">Here's my contact</div>
By using the hash, it'll auto scroll to an element with that id (or an anchor with that name
attribute). If you want it to scroll smoothly you can enhance the scroll effect with a javascript library, like jquery. See this question: How to scroll HTML page to given anchor using jQuery or Javascript?
通过使用散列,它会自动滚动到具有该 id 的元素(或具有该name
属性的锚点)。如果您希望它平滑滚动,您可以使用 javascript 库(如 jquery)增强滚动效果。看到这个问题:How to scroll HTML page to given anchor using jQuery or Javascript?
回答by LNendza
You can jump to it with HTML via:
您可以通过以下方式使用 HTML 跳转到它:
<a href="#tips">Visit the Useful Tips Section</a>
You can do it with CSS via:
您可以通过以下方式使用 CSS 来实现: