问题
The scrollHash()
function below is intended to scroll to a target anchor while adjusting the position to reflect both the fixed menu and desired margin-top
.
The function works properly in Chrome, however it only works in Firefox if a mouseout
event occurs before the function is completed (accounting for the function's duration
and setTimeout()
). Otherwise, if the mouse continues hovering over the link in Firefox throughout the function’s execution, the function fails to complete the second step of adjusting the position (subtracting the fixed menu’s height from offset().top
).
It is worth noting that the problem doesn’t present in JSFiddle + Firefox (using the identical code and version of jQuery, 1.9.1), and I'm running Firefox version 69.0.3 (64-bit). Fiddle available here: https://jsfiddle.net/chayanyc/otkLa90x/
Code Snippets
CSS:
body {margin: 0; padding: 0; height: 100%; overflow-x: hidden;}
* {box-sizing: border-box;}
.header_container {height: var(--targetPosition); width: 100vw; margin: 0; padding: 0; position: fixed; top: 0; display: block;}
.main {margin-top: var(--topWrapper); width: 100%;}
.Section {padding: var(--sectPadding) 0; width: 100%;}
@media (max-width: 600px) {
:root {
--sectPadding: 5rem;
}
}
@media (min-width: 600px) {
:root {
--sectPadding: 9.5rem;
--targetPosition: 9.3rem;
}
}
JavaScript:
// SCROLL HASH FUNCTIONS //
window.onhashchange = scrollHash;
function scrollHash() {
menuHeight = document.getElementById('header').offsetHeight;
$('.TargetMark').removeClass('TargetMark')
if (window.location.hash) {
$(window.location.hash).addClass('TargetMark')
$('html, body').animate({
scrollTop: $('.TargetMark').offset().top - menuHeight
}, 100);
}
}
// SET MARGIN TOP //
var headerHeight;
function setTarget() {
headerHeight = document.getElementById('header').offsetHeight;
headerHeight = headerHeight + "px";
document.documentElement.style.setProperty('--topWrapper', headerHeight);
}
$(document).ready(function () {
setTarget();
});
$(window).resize(function () {
setTarget();
});
console.log output
// SAME OUTPUT IN CHROME VS. FIREFOX
var offset = $('.TargetMark').offset();
console.log( (offset.top - topHeight) );
// DIFFERING OUTPUT IN CHROME VS. FIREFOX
var $window = $(window);
$(window).on('scroll', function () {
$topOffset = $(this).scrollTop();
console.log($topOffset);
});
来源:https://stackoverflow.com/questions/58617731/scrolltop-with-jquery-offset-not-working-properly-in-firefox-unless-mouseout-occ