jQuery实现滚动显示/隐藏回到顶部按钮的问题及代码调试
Let's fix your code first, then tackle all your questions one by one—this is a super common issue with an easy fix!
Core Problem: Typo in jQuery Method
Your code isn't working because you used the wrong method name. You wrote $(this).scrollToTop() but jQuery's method to get the vertical scroll position is scrollTop() (no "To" in the middle). That's why your condition never triggers correctly.
Fixed Full Code
First, make sure your button starts hidden (add this CSS):
#scrollToTop { display: none; /* Hide by default */ position: fixed; bottom: 20px; right: 20px; padding: 10px 15px; background: #333; color: white; text-decoration: none; border-radius: 4px; }
Then the corrected jQuery (plus a bonus smooth scroll to top):
<a href="#" id="scrollToTop">Back to Top</a> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <script> $(window).scroll(function() { // Use scrollTop() instead of scrollToTop() if ($(this).scrollTop() > 75) { $('#scrollToTop').fadeIn(); } else { $('#scrollToTop').fadeOut(); } }); // Add smooth scroll functionality when clicking the button $('#scrollToTop').click(function(e) { e.preventDefault(); // Stop default anchor jump $('html, body').animate({ scrollTop: 0 }, 300); // Animate to top over 300ms }); </script>
Answers to Your Questions
Do I need to wrap the anchor in a div and use the div's ID for fade effects?
Nope! You can directly target the<a>tag with its ID. ThefadeIn()/fadeOut()methods work perfectly on anchor elements as long as they have the right initialdisplay: nonestyle. Wrapping it in a div is only necessary if you have specific layout needs (like grouping elements or adding extra container styling)—it's not required for the core visibility functionality.If $(this) pointed to #scrollToTop, could I use this.fade methods directly?
First, in your scroll event,$(this)refers to thewindowobject, not the button. Even if it did point to the button,thisis a raw DOM element, not a jQuery object. jQuery methods likefadeIn()only work on jQuery-wrapped elements, so you'd need to write$(this).fadeIn()instead ofthis.fadeIn().Do I need to wrap the button in a div and manipulate the div instead?
No, this is unnecessary. Directly manipulating the anchor tag is simpler and achieves the same result. Save the div wrapping for cases where you need to control the button's positioning alongside other elements, or add container-specific styles.
内容的提问来源于stack exchange,提问作者The Dude man




