Jquery scrollTop动画不工作"无法读取属性'top'无风

Jquery scrollTop animation not working .... "Cannot read property 'top' of undefind

本文关键字:属性 读取 top 无风 工作 scrollTop quot Jquery 动画      更新时间:2023-09-26

我的jquery动画scrollTop不工作。当我单击<a>时,它只带我到锚点,没有任何动画。有人能提出解决方案吗?当我运行网页时,会显示错误"Uncaught TypeError: Cannot read property 'top' of undefined"

这里是我的html代码:

<div class="BackgroundImg"></div>
<head>
    <title>Ryan Robert 1.0</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
    <link type="text/css" rel="stylesheet" href="style.css">

    <script type="text/javascript" >
         $(function(){
          $("a").click(function(){
             if(this.hash){
                 var hash = this.hash.substr(1);
                 var $toElement = $("a[name="+hash+"]");
                 var toPosition = $toElement.position().top;
                 $("html,body").animate({
                     scrollTop : toPosition         
                 },2000,"easeOutExpo");
                  return false;
             }
             });
      });
    </script>

身体部位:

        <ul>
            <li><div id="menus">
                .home</div></li>
            <li><a href="#secondBox"><div id="menus">
                .project</div></a></li>
            <li><a href="#thirdBox"><div id="menus">
                .skills</div></a></li>
            <li><a href="#forthBox"><div id="menus">
                .contact</div></a></li>
        </ul>
    </div>
    <div id="firstBox">
        <div id="profileDescriptionBox">
            <div id="profileDescription">
                <h1>.Welcome!</h1>

问题是您没有使用prevent-default!

因此,您实际上像浏览器中的默认值一样被锚定。

对于一个平滑的动画,我建议你这样做:

$(document).ready(function(){
  $("a").click(function(e){
      e.preventDefault();
      var offset = $(this.hash).offset();
      if (!offset) {
      	return;
      }
      $("html,body").animate({
        scrollTop : offset.top         
      },2000);
  });
});
.box {
  min-height: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<ul>
  <li><a href="#first-box">First box</a></li>
  <li><a href="#second-box">Second box</a></li>
  <li><a href="#third-box">Third box</a></li>
</ul>
<div id="first-box" class="box">
   First box
</div>
<div id="second-box" class="box">
   Second box
</div>
<div id="third-box" class="box">
   Third box
</div>
<div class="box">
 Just extra to fill out
</div>

或jsfiddle.net

https://jsfiddle.net/4xuvjuq5/

您尝试过使用offset().top吗?

var toPosition = $toElement.offset().top;