在单个条件下检查滚动顶部和 id 偏移量

checking both scrollTop and id offset in single condition

本文关键字:id 偏移量 顶部 滚动 单个 条件下 检查      更新时间:2023-09-26

我想检查滚动位置是否大于 350,并且在相同条件下菜单粘性偏移位置为 92。我给了我的一段代码

 $(window).scroll(function(){
if(($(document).scrollTop() >= 350) && (($('.menuSticky').offset().top )==92)) {
           console.log('true');
           $('.dropdown').hover(function() {
          $('.secMenu').hide();
             $(this).toggleClass("open");
        }).mouseleave(function(){
          $('.secMenu').show();
        });    
       }
      });   

尝试将 $(document).scrollTop() 替换为 $(window).scrollTop()

 $(window).scroll(function() {
   if (($(window).scrollTop() >= 350) && (($('.menuSticky').offset().top) == 92)) {
     console.log('true');
     $('.dropdown').hover(function() {
       $('.secMenu').hide();
       $(this).toggleClass("open");
     }).mouseleave(function() {
       $('.secMenu').show();
     });
   }
 });

您的代码没有任何问题,在以下代码片段中,我在没有任何编辑的情况下使用您的代码,但我给出了.menuSticky margin-top:92px;,因此您的第二个条件将为真并且工作正常.

$(window).scroll(function(){
  if(($(document).scrollTop() >= 350) && (($('.menuSticky').offset().top )==92)) {
    console.log('true');
  }
}); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="menuSticky" style="margin-top:92px"> Menu </div>
<div style="height:1000px;">Some content</div>