我是jQuery新手。我在同一页上有两个功能:
- 一个是ID的平滑滚动
- 另一个显示用户滚动设置距离后的"返回顶部"元素
这些函数可以自己工作,但当我如下图所示将它们组合在一起时,"返回顶部"函数不起作用
我想我错过了一些显而易见的东西,需要一些帮助。谢谢
更新:这个小提琴显示了问题:
返回页首jsfiddle如果平滑滚动块被禁用,则返回页首功能正常工作。
jQuery(document).ready(function(){
//smooth scrolling
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top -150}, 900, 'swing', function () {
window.location.hash = target;});
});
// Show or hide the back to top footer button
$(window).scroll(function() {
if ($(this).scrollTop() > 200) {
$('.go-top').fadeIn(200);
} else {
$('.go-top').fadeOut(200);
}
});
// Animate the scroll to top
$('.go-top').click(function(event) {
event.preventDefault();
$('html, body').animate({scrollTop: 0}, 900);
});
});
Hi@DavidCara只需添加
<div id="top"></div>
在立即标记<body>
之后,它将挑衅地工作。
请参阅更新的jsfiddle Here
直接在html标记中使用这个简单的代码。
<a onclick="$('html, body').animate({scrollTop: 0}, 900);" href="javascript:;">back to top </a>