jQuery 在单击项目时向下滚动

jQuery scrolling down on click of an item

本文关键字:滚动 项目 单击 jQuery      更新时间:2023-09-26

我有一个很长的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;
      });
  });
});