jQuery 在单击项目时向下滚动
jQuery scrolling down on click of an item
我有一个很长的HTML页面,里面有内容。我试图实现的是,当有人单击标题中的菜单项时,页面应该向下滚动到锚元素。我尝试了很多事情,但没有运气。我不懂JavaScript。这是我尝试过的:
_header.html.erb
<div class="header_pad">
<nav class="top-bar" data-topbar role="navigation">
<ul class="title-area">
<li class="name">
<h1><a href="/">The Investors' Club</a></h1>
</ul>
<section class="top-bar-section">
<ul class="left">
<li><a id="result" href="#contact">Contact</a></li>
</ul>
</section>
</nav>
</div>
应用.js
function scrollToAnchor(aid){
var aTag = $("a[name='"+ aid +"']");
$('html,body').animate({scrollTop: aTag.offset().top},'slow');
}
$("#result").click(function() {
scrollToAnchor('contact');
});
索引.html.erb
<div id="contact">
<%= image_tag("contact_us.png", :alt => "Forex Investment Contact") %></br>
<p class="small-11 small-centered columns">
Skype is free and more convenient, give us a call or send us an email if you happen to have some questions. We will
be glad to hear from you.
</br>
<%= image_tag("skype.png", :alt => "skype") %> OR
<b>100forexinvestors@gmail.com</b>
</p>
</div>
实时页面: https://infinite-oasis-2303.herokuapp.com所以我希望当我单击标题中的"联系人"时,它会平滑地向下滚动到页面下方的联系人锚点。有什么帮助吗?
编辑:我让它与我发布的 js 一起工作作为答案。然而。如果我单击后退按钮并单击另一个链接,则在我重新加载页面之前,动画将不再起作用。看起来javascript只加载一次。我该如何消除它?
似乎你有错别字<a name"test"></a>
.尝试将其更改为<a name="test"></a>
编辑
由于问题已编辑,因此application.js
以下示例:
$(document).ready(function() {
$('.top-bar-section a').click(function(e) {
e.stopPropagation();
var eid = $(this).attr('href');
var top = $(eid).offset().top;
$('html, body').animate({ scrollTop: top }, 'slow');
});
});
确保定位点href
和目标id
相等。例如:<a href="#contact">
用于<div id="contact">
这可能会
有所帮助,
function scrollToAnchor(aid){
var aTag = $("a[name='"+ aid +"']");
$('html,body').animate({scrollTop: aTag.offset().top},500);
将"time"作为第二个参数传递给 animate 函数。它应该在那么长的"时间"内导航到目标位置。从而有助于平稳过渡。
好的。我让它与这段 js 一起工作:
$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash;
var $target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 1200, 'swing', function () {
window.location.hash = target;
});
});
});
相关文章:
- 在不向上滚动的情况下向列表框中添加项目
- 取消选择滚动启动时的所有列表视图项目
- 如何滚动到DIV顶部表格的最后一个位置(项目10)
- 将引导程序下拉选择滚动条居中到所选项目
- 在SAPUI5项目中使用sap.ui.ux3.Shell时,无法在iphone上滚动
- 用Javascript将焦点设置在select元素上会将第一个项目滚动到视图之外
- 滚动到列表中的特定项目,然后滚动到列表的下一个特定项目
- 当目标处于顶部滚动状态时,如何从菜单中激活项目
- 我们可以使用 iscroller 一次滚动固定的 3 个列表项项目吗?
- 在离子框架中选择带有离子滚动的中间项目
- 加载更多项目,而无需滚动或按“查看更多”,就像在Facebook中使用JS一样
- 鼠标悬停时垂直自动滚动 - 就像“项目赠品”deviantart.com 一样
- 如果项目溢出,则动态滚动
- jQuery Tools 可滚动:屏幕上有 3 个项目,但一次滚动一个
- jScrollPane (jQuery) 同时滚动内容窗格 API 中的所有项目
- 剑道UI移动列表视图无尽滚动仅显示一个项目
- 使 HTML5 可拖动项目滚动页面
- Javascript 滚动视差掩盖页面上的其他项目
- jQuery计算项目在可滚动窗口中的位置并滚动到它
- 无限滚动:项目选择器中的js代码