jQuery平滑滚动异常:点击按钮随机滚动或跳至顶部求助
Hey there, let's tackle that weird scrolling issue you're seeing with your "careers" and "contact us" buttons. After looking over your code and checking the site, I've spotted a couple of key issues causing the random scrolls or jumps to the top:
What's Causing the Problem?
Conflict Between CSS and jQuery Smooth Scrolling
You've gotscroll-behavior: smoothset on yourbodyandhtmlelements in CSS, AND you're using jQuery'sanimate()method to handle smooth scrolling. These two approaches fight each other, resulting in the inconsistent scroll behavior you're experiencing.Potential Target Position Mismatch
While less critical here, if you have a fixed header or navigation bar, thetarget.offset().topcalculation might be positioning content under that bar—but the main culprit is definitely the scroll behavior conflict.
How to Fix It
Option 1: Remove CSS Native Smooth Scrolling (Recommended)
Since you're already using a custom jQuery scroll implementation, stick with one system. Remove the CSS scroll behavior to eliminate the conflict:
Update your CSS for body, html:
body, html { width: 100%; height: 100%; overflow-x: hidden; /* Delete this line: scroll-behavior: smooth; */ -webkit-overflow-scrolling: touch; }
Option 2: Switch to Native Scroll (If You Want to Keep CSS Smooth Scrolling)
If you prefer the CSS scroll-behavior approach, replace your jQuery scroll logic with native browser scrolling. This keeps things clean and avoids conflicts:
Replace your existing "Smooth scrolling using jQuery easing" code block with this:
// Smooth scrolling using native browser behavior $('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function(e) { e.preventDefault(); const target = document.querySelector(this.hash); if (target) { target.scrollIntoView({ behavior: 'smooth', block: 'start' // Adjust to 'center' if you want vertical centering }); } });
Bonus: Fix Fixed Header Occlusion (If Needed)
If you end up keeping the jQuery scroll and notice your target sections are hidden under a fixed header, adjust the scroll position by subtracting the header's height. For example, if your header is 70px tall:
$('html, body').animate({ scrollTop: target.offset().top - 70 // Subtract your header height here }, 1000, "easeInOutExpo");
Test It Out
After making either of these changes, click your "careers" and "contact us" buttons again—they should smoothly and accurately scroll to the correct anchor sections without any random jumps.
内容的提问来源于stack exchange,提问作者Strahinja

