使元素仅在向下滚动到 ***px 时可见

Dee*_*mat 5 jquery

我在我的网站上使用滚动到顶部按钮。我正在使用这个 Jquery

    $(window).scroll(function() {
    if ($(this).scrollTop()) {
        $('#cttm:hidden').stop(true, true).fadeIn();
    } else {
        $('#cttm').stop(true, true).fadeOut();
    }
});


  $(document).ready(function(){
      var bottom = ($(window).outerHeight() - $(window).height()) - 150; // 150 pixel to the bottom of the page; 
      $(window).scroll(function(){
          if ($(window).scrollTop() >= bottom ) {
                  $("#cttm").fadeTo("slow",.95);
             } else {
                  $("#cttm").fadeOut("slow");
             }
      });

      $("#cttm").click(function(){
          $('html, body').animate({scrollTop:0}, 'slow');
          $("#cttm").fadeOut("slow");
      });
  });
Run Code Online (Sandbox Code Playgroud)

这个 Jquery 效果很好,但我希望元素只在我们从顶部滚动到 200px 或类似的东西时出现。有没有办法用 JQuery 做到这一点?

Den*_*ret 6

你不需要窗口高度来做到这一点。

var isVisible = false;
$(window).scroll(function(){
     var shouldBeVisible = $(window).scrollTop()>200;
     if (shouldBeVisible && !isVisible) {
          isVisible = true;
          $('#mybutton').show();
     } else if (isVisible && !shouldBeVisible) {
          isVisible = false;
          $('#mybutton').hide();
    }
});
Run Code Online (Sandbox Code Playgroud)

演示:http : //jsfiddle.net/dystroy/gXSLE/