简体   繁体   English

jQuery:从顶部开始执行大于150px

[英]jQuery: Executing if more than 150px from top

I need help to execute the mouseenter and mouseleave function only if you have scrolled 150px or more ... 仅当您滚动150像素或更多时,我才需要帮助来执行mouseentermouseleave函数...

    $(document).ready(function(){

            $(document).scroll(function() {
                var top = $(document).scrollTop();

        if (top > 150) $(".menywrapper").mouseenter(function(){
$(".main-navigation").removeClass( "nav-closed", 200, "linear" );  
 });
        if (top > 150) $(".menywrapper").mouseleave(function(){
$(".main-navigation").addClass( "nav-closed", 200, "linear" );  }); 
 });

Don't bind mouseenter/mouseleave on each scroll event, do it once and check for a var : 不要在每个滚动事件上绑定mouseenter / mouseleave,只做一次并检查var:

$(document).ready(function(){
     var top = 0;
     $(document).scroll(function() {
         top = $(document).scrollTop();
     });

     $(".menywrapper").mouseenter(function(){
         if(top>150)
             $(".main-navigation").removeClass( "nav-closed", 200, "linear" );  
     });

     // same for mouseleave

});

Move the if condition inside eventhandler 在事件处理程序中移动if条件

$(".menywrapper").mouseenter(function(){
   if (top > 150) 
      $(".main-navigation").removeClass( "nav-closed", 200, "linear" );  
});
$(".menywrapper").mouseleave(function(){
   if (top > 150) 
      $(".main-navigation").addClass( "nav-closed", 200, "linear" );  }); 
 });

You can use a boolean to keep track if you are above or below 150 px; 如果您高于或低于150像素,则可以使用布尔值进行跟踪;

$(document).ready(function() {
    var below_150 = false;

    $(document).scroll(function() {
        var top = $(document).scrollTop();
        below_150 = (top > 150);
    }

    $(".menywrapper").hover(
        function() {
            if( below_150 )
            {
                $(".main-navigation").removeClass( "nav-closed", 200, "linear" );
            }
        },
        function() {
            if( below_150 )
            {
                $(".main-navigation").addClass( "nav-closed", 200, "linear" );
            }
        }
    )
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM