scrollTop with jQuery offset not working properly in Firefox unless mouseout occurs

不羁的心 提交于 2019-12-13 03:10:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!