滚动后隐藏div

时间:2018-01-17 06:45:13

标签: jquery html css

我有一个页面,其中有一个帖子的主体,但点击一个链接,它将滚动到一个隐藏的div视图。我的问题是如何在滚过它之后隐藏div,或者一旦它离开ViewPort,因为我当前的jQuery代码根本不起作用。

这是我的代码:

$(document).ready(function() {
  $('.about').hide();
  $('.link2about').on('click', function(e) {
    e.preventDefault();
    $('.about').show();
    $('html, body').animate({
      scrollTop: $('.about').offset().top
    }, 1000, 'swing');
    return false;
  });
  $(window).scroll(function() {
    if ($('.about').is(':visible')) {
      $('.about').show();
    } else {
      $('.about').hide();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="link2about"> about </div>
<div class="posts">
  body content here body content here body content here body content here body content here body content here body content here body content here body content here body content here body content here body content here
</div>
<div class="about">
  about content here about content here about content here about content here about content here about content here
</div>

1 个答案:

答案 0 :(得分:0)

使用offset().top获取element顶部,然后使用语句比较窗口scrollTop和元素offset top

$(document).ready(function() {

  var elTop = $('.about').offset().top; // get element top

  $('.about').hide();
  $('.link2about').on('click', function(e) {
    e.preventDefault();
    $('.about').show();
    $('html, body').animate({
      scrollTop: $('.about').offset().top
    }, 1000, 'swing');
    return false;
  });
  $(window).scroll(function() {

    if ($(window).scrollTop() > elTop) { // If window scroll top greater than element top
      $('.about').hide();
    }

  });
});
.link2about {
  color: red;
}

body {
  height: 2000px;
}

.about {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="link2about"> about </div>
<div class="posts">
  body content here body content here body content here body content here body content here body content here body content here body content here body content here body content here body content here body content here
</div>
<div class="about">
  about content here about content here about content here about content here about content here about content here
</div>