我正在尝试添加 jQuery 平滑滚动,单击按钮使我到达页面顶部,但动画不起作用。
jQuery(function( $ ){
//Check to see if the window is top if not then display button
$(window).scroll(function(){
if ($(this).scrollTop() > 800) {
$('.fa-chevron-up').fadeIn();
} else {
$('.fa-chevron-up').fadeOut();
}
});
//Click event to scroll to top
$('.fa-chevron-up').click(function(){
$('html,body').animate({scrollTop : 0}, 800);
return false;
});
});
这是滚动时出现的按钮 -
<a href="#" class="scrolltotop"><i class="fas fa-chevron-up"></i></a>
尝试了 jQuery(文档) 仍然没有成功。有什么想法吗?
最佳答案
jQuery(function($) {
//Check to see if the window is top if not then display button
$(window).scroll(function() {
if ($(this).scrollTop() > 100) {
$('.scrolltotop').fadeIn();
} else {
$('.scrolltotop').fadeOut();
}
});
//Click event to scroll to top
$('.scrolltotop').click(function(e) {
$('html, body').animate({scrollTop : 0}, 800);
e.preventDefault();
});
});
a.scrolltotop {
bottom: 10px;
display: none;
position: fixed;
right: 10px;
}
html {
overflow-y: scroll;
}
div.content {
height: 400vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content"> </div>
<a href="#" class="scrolltotop"><i class="fas fa-chevron-up"></i>^ Up</a>
动画不起作用,因为它没有被调用。页面滚动回顶部的原因是您实际上导航到了未定义的 anchor (href="#"
)。
更改此:
jQuery('.fa-chevron-up').click(function(){
对此:
jQuery('.scrolltotop').click(function() {
由于 font-awesome 图标通常通过将字符指定为应用类的元素的伪元素来工作,因此如果直接单击该图标,它可能会按预期工作。在任何情况下,您都应该通过 .scrolltotop
选择器将点击处理程序应用到 a
标记元素。
注意:我还更新了淡入淡出行为的选择器。
关于javascript - jQuery 动画到顶部功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50534931/