禁用在页面上向后滚动

时间:2015-12-14 18:43:02

标签: javascript jquery html css html5

一旦超出某个点,我需要禁用在html页面上向上滚动的功能。我还需要一种机制来返回到所述页面的顶部。

我已尝试使用以下代码完成此操作,但它对我来说还不起作用,因为页面是响应式的(因此点的位置可能会随窗口的大小而变化)。

$(function() {
    var scrollPoint = 200;
    var scrolledPast = false;
    $(window).scroll(function() {
        $(window).scrollTop() > scrollPoint ? scrolledPast = true : '';
        $(window).scrollTop() < scrollPoint && scrolledPast == true ?     
        $(window).scrollTop(scrollPoint) : '';
    }).scroll();
});  

可以用Javascript / JQuery完成吗?

1 个答案:

答案 0 :(得分:5)

var minScroll = 200;
var scrollPoint = 0;

function setPage(id) {
  scrollPoint = $("#" + id).offset().top;
  document.location.href = "#" + id;
}

$(function() {
  $(window).on("scroll", function() {
    var current = $(window).scrollTop();
    if (scrollPoint >= minScroll) {
      if (current < scrollPoint) $(window).scrollTop(scrollPoint);
      else {
        //scrollPoint = $(window).scrollTop();
      }
    } else {
      //scrollPoint = $(window).scrollTop();
    }
  });

  $("#return").on("click", function() {
    scrollPoint = 0;
    $(window).scrollTop(0);
  });

  wave("page1");
  wave("page2");
  wave("page3");
});

function wave(id) {
  var maxWave = 30;
  var minWave = 2;

  for (var i = 0; i < 50; i++) {
    var waveSize = Math.floor(Math.random() * (maxWave - minWave) + minWave);
    var j = 0;

    for (j; j < waveSize; j++) {
      for (var k = 0; k < j; k++) {
        $("#" + id).append("#");
      }
      console.log(j + " vs " + waveSize);
      if (j == waveSize - 1) $("#" + id).append(")");
      else $("#" + id).append("\\");

      $("#" + id).append("<br />");
    }

    for (j = j - 2; j >= 0; j--) {
      for (var k = 0; k < j; k++) {
        $("#" + id).append("#");
      }
      $("#" + id).append("/<br />");
    }
  }
}
#return {
  position: fixed;
  top: 55px;
  right: 5px;
}
#pg1 {
  position: fixed;
  top: 75px;
  right: 5px;
}
#pg2 {
  position: fixed;
  top: 95px;
  right: 5px;
}
#pg3 {
  position: fixed;
  top: 115px;
  right: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="return">Return To Top</button>
<button id="pg1" onclick="setPage('page1');">Page 1</button>
<button id="pg2" onclick="setPage('page2');">Page 2</button>
<button id="pg3" onclick="setPage('page3');">Page 3</button>

<div id="page1">Page 1
  <br />
</div>
<div id="page2">Page 2
  <br />
</div>
<div id="page3">Page 3
  <br />
</div>