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中我没有任何锚…非常感谢。