简体   繁体   English

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

[英]jQuery animate to top function is not working

I'm trying to add jQuery smooth scrolling, clicking the button gets me to the top of the page but the animation 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;
    });

});

This is the button that appears when scrolling - 这是滚动时出现的按钮-

<a href="#" class="scrolltotop"><i class="fas fa-chevron-up"></i></a>

Tried jQuery(document) still no luck. 尝试过jQuery(document)仍然没有运气。 Any ideas? 有任何想法吗?

 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> 

The animation is not working because it is not being called. 动画不起作用,因为未调用它。 The reason the page scrolls back to the top is because you are effectively navigating to an undefined anchor ( href="#" ). 页面滚动回到顶部的原因是因为您正在有效地导航到未定义的锚点( href="#" )。

Change this: 更改此:

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

To this: 对此:

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

Since font-awesome icons generally work by assigning a character as a pseudo-element of the element the classes are applied to, it is possible that if you click directly on the icon, it might work as expected. 由于超棒字体图标通常通过将字符分配为应用类的元素的伪元素来工作,因此,如果直接单击图标,则可能会按预期工作。 In any case, you should apply the click handler to the a tag element via the .scrolltotop selector. 在任何情况下,你应该申请单击处理到a通过标签元素.scrolltotop选择。

Note: I've also updated the selectors for the fade behavior. 注意:我还更新了淡入淡出行为的选择器。

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

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