Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/426.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery外部链接锚定动画_Javascript_Jquery - Fatal编程技术网

Javascript jQuery外部链接锚定动画

Javascript jQuery外部链接锚定动画,javascript,jquery,Javascript,Jquery,找不到正确答案。 我想打开页面,然后动画滚动到我调用的ID 这是我的密码 JQuery $(window).bind("load", function () { var urlHash = window.location.href.split("#")[1]; $('html,body').animate({ scrollTop: $('a[href="#' + urlHash + '"]').offset().top}, 100

找不到正确答案。 我想打开页面,然后动画滚动到我调用的
ID

这是我的密码

JQuery

   $(window).bind("load", function () {
              var urlHash = window.location.href.split("#")[1];
                $('html,body').animate({ scrollTop: $('a[href="#' + urlHash + '"]').offset().top}, 1000);
    }); 
Html

<div class="space"></div>
<div id="anchor">This is anchor</div>
然后jQuery不起作用,所以我将以下代码粘贴到控制台

 $('html,body').animate({ scrollTop: $('a[href="#' + anchor+ '"]').offset().top}, 1000);
错误是

TypeError:无法读取未定义的属性“top”

我如何解决这个错误?谢谢

此代码有效:

演示:

我向锚添加了href,并将脚本移动到HTML

$(window).bind("load", function () {
          var urlHash = window.location.href.split("#")[1];
            $('html,body').animate({ scrollTop: $('a[href="#' + urlHash + '"]').offset().top}, 1000);
      });
此代码适用于:

演示:

我向锚添加了href,并将脚本移动到HTML

$(window).bind("load", function () {
          var urlHash = window.location.href.split("#")[1];
            $('html,body').animate({ scrollTop: $('a[href="#' + urlHash + '"]').offset().top}, 1000);
      });

标记中的锚在哪里?你的小提琴有两个主要问题:没有带有a href的锚,也没有window.location.hashI在本地测试,我刚刚插入。我使用的
id=“anchor”
应该改用
name='anchor'
还是a href?thanks@undefined是的,我发现了我的错误!我在JS中使用了href,但在html中我没有任何锚…非常感谢。你的标记中锚在哪里?你的小提琴有两个主要问题:没有带有a href的锚,也没有window.location.hashI在本地测试,我刚刚插入。我使用的
id=“anchor”
应该改用
name='anchor'
还是a href?thanks@undefined是的,我发现了我的错误!我在JS中使用了href,但在html中我没有任何锚…非常感谢。