2017-03-03 46 views
0
<script> 
$(function() { 
    $(".griditem").slice(0, 12).show(); 
    $("#loadMore").on('click', function (e) { 
     e.preventDefault(); 
     $(".griditem:hidden").slice(0, 12).slideDown(); 
     if ($(".griditem:hidden").length == 0) { 
      $("#load").fadeOut('slow'); 
     } 
     $('html,body').animate({ 
      scrollTop: $(this).offset().top 
     }, 1500); 
    }); 
}); 
</script> 

有了這一點的代碼,它目前需要你按下一個按鈕來加載更多divs,但是當滾動到視圖時如何使它自動執行,所以你不必按下按鈕?如何在進入視圖時更改此代碼以使其滾動?

http://codepen.io/anon/pen/KWMKZx

+0

那是因爲你把它放到你的'onClick'事件處理程序下。你應該把它放在外面。 –

回答

0

您可以將事件偵聽scroll事件,這樣你可以檢查當用戶滾動到時候你想。

var flag = true; 
$(document).scroll(function(){ 
    var st = $(document).scrollTop(); 
    var viewportHeight = $(window).height(); 
    var offset = $('#loadMore').offset().top; //You can change #loadMore for whatever element you want to fire the event when the user scrolls to. 
    if (st + viewportHeight > offset && flag){ //You can change the number 10. This means "When scrolled 10 pixels more than the top border of #loadMore" 
    $('#loadMore').trigger("click"); 
    flag = false; //This flag is just so that the click doesnt get triggered a lot of times unnecesary. 
    window.setTimeout(function(){flag=true;},200); 
    } 
}); 

這裏是Code

+0

你可以把它放在codepen –

+0

@AchmedZuzali我已經上傳了codepen現在。我還對我的代碼做了一些修改,添加了也是需要的變量'viewportHeight'。 –

0

試試這個

function loadIt(){ 
    $(".griditem").slice(0, 12).show(); 
     $(".griditem:hidden").slice(0, 12).slideDown(); 
     if ($(".griditem:hidden").length == 0) { 
      $("#load").fadeOut('slow'); 
     } 
     $('html,body').animate({ 
      scrollTop: $(this).offset().top 
     }, 1500); 
} 
$(window).scroll(function(){ 
    if($(window).scrollTop() + $(window).height() > $(document).height() -20) { 
     loadIt(); 
    } 
}); 
+0

你可以把它放在一個codepen中,因爲它不適合我 –