[英]jQuery external link anchor animate
Could not find a correct answer. 找不到正确答案。 I'd like to open the page then animate scrolled to the
ID
I called. 我想打开页面,然后以动画方式滚动到我叫的
ID
。
here is my code. 这是我的代码。
JQuery jQuery查询
$(window).bind("load", function () {
var urlHash = window.location.href.split("#")[1];
$('html,body').animate({ scrollTop: $('a[href="#' + urlHash + '"]').offset().top}, 1000);
});
Html HTML
<div class="space"></div>
<div id="anchor">This is anchor</div>
css 的CSS
.space{height:800px;}
#anchor{font-size:25px;height:800px;}
then jQuery is not working, so I pasted the following code to console jQuery无法正常工作,因此我将以下代码粘贴到控制台
$('html,body').animate({ scrollTop: $('a[href="#' + anchor+ '"]').offset().top}, 1000);
The error says 错误说
TypeError: Cannot read property 'top' of undefined
TypeError:无法读取未定义的属性“ top”
http://jsfiddle.net/4mjmw/1/ http://jsfiddle.net/4mjmw/1/
How could I solve this error? 我该如何解决这个错误? thanks
谢谢
This code works: http://jsfiddle.net/4mjmw/4/ 此代码有效: http : //jsfiddle.net/4mjmw/4/
Demo: http://jsfiddle.net/4mjmw/4/show/#abc 演示: http : //jsfiddle.net/4mjmw/4/show/#abc
I added an href to the anchor and moved the script to HTML. 我向锚添加了href,并将脚本移至HTML。
$(window).bind("load", function () {
var urlHash = window.location.href.split("#")[1];
$('html,body').animate({ scrollTop: $('a[href="#' + urlHash + '"]').offset().top}, 1000);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.