繁体   English   中英

jQuery动画到顶部功能不起作用

[英]jQuery animate to top function is not working

我正在尝试添加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(document)仍然没有运气。 有任何想法吗?

 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">&nbsp;</div> <a href="#" class="scrolltotop"><i class="fas fa-chevron-up"></i>^ Up</a> 

动画不起作用,因为未调用它。 页面滚动回到顶部的原因是因为您正在有效地导航到未定义的锚点( href="#" )。

更改此:

jQuery('.fa-chevron-up').click(function(){

对此:

jQuery('.scrolltotop').click(function() {

由于超棒字体图标通常通过将字符分配为应用类的元素的伪元素来工作,因此,如果直接单击图标,则可能会按预期工作。 在任何情况下,你应该申请单击处理到a通过标签元素.scrolltotop选择。

注意:我还更新了淡入淡出行为的选择器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM