2013-03-23 28 views
6

我上一個項目,我需要聽scroll事件的工作。我不知道什麼是更好的方法..的jQuery的setInterval或滾動

1日法

function scroll() { 
    if ($(window).scrollTop() > 200) { 
     top.fadeIn(); 
    } else { 
     top.fadeOut(); 
    } 
    if (menuVisible) { 
     quickHideMenu(); 
    } 
} 

第二個方法

 function scroll() { 
      didScroll = true; 
     } 

     setInterval(function() { 
      if (didScroll) { 
       didScroll = false; 
       if ($(window).scrollTop() > 200) { 
        top.fadeIn(); 
       } else { 
        top.fadeOut(); 
       } 
       if (menuVisible) { 
       quickHideMenu(); 
       } 
      } 
     }, 250); 

謝謝:)

+0

HTTP: // ejohn。 org/blog/learning-from-twitter /閱讀這篇文章,由Twitter的創建者John Resig – 2013-03-23 19:29:23

+0

@MohammadAdil我已閱讀它,這是什麼讓我想到這個問題.. – 2013-03-23 19:30:50

+2

@LuckySoni你最終做了什麼? – 2013-03-24 17:53:30

回答

17

都不是。我只是讀了關於JS/jQuery模式。沒有爲窗口滾動事件爲例:jQuery Window Scroll Pattern

var scrollTimeout; // global for any pending scrollTimeout 

$(window).scroll(function() { 
    if (scrollTimeout) { 
     // clear the timeout, if one is pending 
     clearTimeout(scrollTimeout); 
     scrollTimeout = null; 
    } 
    scrollTimeout = setTimeout(scrollHandler, 250); 
}); 

scrollHandler = function() { 
    // Check your page position 
    if ($(window).scrollTop() > 200) { 
     top.fadeIn(); 
    } else { 
     top.fadeOut(); 
    } 
    if (menuVisible) { 
     quickHideMenu(); 
    } 
}; 
從這裏

原:Javascript Patterns

+0

Javascript樣式庫是黃金! – DawnPaladin 2016-07-18 18:42:52

0

它的工作對我罰款

<style type="text/css"> 
    .scrollToTop { 
     width:100px; 
     height:130px; 
     padding:10px; 
     text-align:center; 
     background: whiteSmoke; 
     font-weight: bold; 
     color: #444; 
     text-decoration: none; 
     position:fixed; 
     top:75px; 
     right:40px; 
     display:none; 
     background: url('arrow_up.png') no-repeat 0px 20px; 
    } 

.scrollToTop:hover{ 
    text-decoration:none; 
} 

</style> 
<script> 
$(document).ready(function(){ 

    //Check to see if the window is top if not then display button 
    $(window).scroll(function(){ 
     if ($(this).scrollTop() > 100) { 
      $('.scrollToTop').fadeIn(); 
     } else { 
      $('.scrollToTop').fadeOut(); 
     } 
    }); 

    //Click event to scroll to top 
    $('.scrollToTop').click(function(){ 
     $('html, body').animate({scrollTop : 0},800); 
     return false; 
    }); 
}); 
</script> 

<a href="#" class="scrollToTop">Scroll To Top</a> 

http://www.paulund.co.uk/how-to-create-an-animated-scroll-to-top-with-jquery

+0

如果不檢查fadeIn()方法是否已經應用到元素,可以嗎? – KeizerBridge 2015-06-26 12:40:31