首页 > 解决方案 > jQuery animate scrollTop 不会在任何浏览器上滚动

问题描述

我正在制作一个网站,当用户单击导航栏的某种按钮时,整个网页应滚动到包含用户选择的信息的部分。但它只是由于某种原因根本行不通。它曾经是,但有什么东西坏了。

导航栏代码:

<ul id="outJS">
 <li>
   <a href="#section0"> Infomratica </a>
 </li>
</ul>

部分代码:

<section id="section0" class="sezione0">
    <div class="container-fluid" style="text-align: center;">
        <div id="heading" class="row" style="margin-top: 125px;">
            <div class="col-md" style="margin-bottom: 80px;">Infomatica</div>
        </div>
        <div class="row justify-content-center">
            <div class="button" id="button-3">
                <div id="circle"></div><a>Infomatica</a>
            </div>
        </div>
    </div>
</section>

应该提供滚动功能的代码是这样的:

$('a[href*="#"]').on("click", function (e) {

        e.preventDefault();

        let target = $($(this).attr("href"));
        console.log(target.length);


        if (target.length) {
          $('html, body').animate({
            scrollTop: $(target).offset().top
          }, 1000);
        }



      });

我已经尝试了所有的可能性,但都没有奏效。

您知道是什么原因造成的,以及如何解决吗?

编辑:

我已经导入了 jQuery

标签: javascriptjqueryhtml

解决方案


您的开始锚标记似乎缺少>. 它应该是:

<a href="#section0">Informatica</a>

下面的工作示例:

$('a[href*="#"]').on("click", function(e) {
  e.preventDefault();
  let target = $($(this).attr("href"));
  if (target.length) {
    $('html, body').animate({
      scrollTop: $(target).offset().top
    }, 1000);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul id="outJS">
 <li>
   <a href="#section0">Informatica</a>
 </li>
</ul>

<section id="section0" class="sezione0">
  <div class="container-fluid" style="text-align: center;">
    <div id="heading" class="row" style="margin-top: 125px;">
      <div class="col-md" style="margin-bottom: 80px;">Informatica</div>
    </div>
    <div class="row justify-content-center">
      <div class="button" id="button-3">
        <div id="circle"></div><a>Informatica</a>
      </div>
    </div>
  </div>
</section>


推荐阅读