当您进入视图时,如何更改此代码以使其滚动?

时间:2017-03-03 20:36:36

标签: jquery scroll

<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>

使用这段代码,它目前要求你按一个按钮来加载更多的div,但是当你滚动到视图中时如何让它自动完成,这样你就不必按下按钮? / p>

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

2 个答案:

答案 0 :(得分:0)

您可以将事件侦听器附加到滚动事件,以便您可以在用户滚动到您想要的位置时进行检查。

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

答案 1 :(得分: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();
   }  
});