手动滚动到id甚至滚动到顶部时更改URL?

时间:2016-06-22 08:13:47

标签: javascript jquery

当我滚动到ID时,是否可以立即更改地址栏中的URL?或者有一个带有多个id的长文档和地址栏上的url更改,当我点击一个新的ID时,即使我从下到上滚动表单。

我使用Change url when manually scrolled to an anchor?

但从下到上滚动时这不起作用。



$(function () {
  var currentHash = "#";
  $(document).scroll(function () {
    $('.block').each(function () {
      var top = window.pageYOffset;
      var distance = top - $(this).offset().top;
      var hash = $(this).attr('id');
      // 30 is an arbitrary padding choice, 
      // if you want a precise check then use distance===0
      if (distance < 30 && distance > -30 && currentHash != hash) {
        window.location.hash = (hash);
        currentHash = hash;
      }
    });
  });
});
&#13;
body {
  margin: 0px;
}
div {
  height: 900px;
  text-align: center;
  padding: 15px;
  background-color: #00f;
}
div:nth-child(even) { background: #ccc; }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>

<div class="block" id="one">Block 1</div>
<div class="block" id="two">Block 2</div>
<div class="block" id="three">Block 3</div>
<div class="block" id="four">Block 4</div>
<div class="block" id="five">Block 5</div>
&#13;
&#13;
&#13;

提前致谢。

1 个答案:

答案 0 :(得分:3)

在您发表评论后,我了解您要实现的目标:

以下代码基于向上/向下滚动。

将存储当前区块并让您“跳跃”#34;块之间:

$(function () {
  var blocksArr = $('.block');
  var lastScrollTop = 0;
  var currentBlock = 0;


  $(document).scroll(function () {
    var st = $(this).scrollTop();
    var hash;

    //make sure it is in the boundaries     
    if (st > lastScrollTop && currentBlock< blocksArr.length -1){
    // downscroll code
         hash = $(blocksArr[++currentBlock]).attr('id');
         window.location.hash = (hash);
    }
    else 
        if (st < lastScrollTop && currentBlock > 0){
    // scrollup code
        hash = $(blocksArr[--currentBlock]).attr('id');
        window.location.hash = (hash);
    }

    lastScrollTop = $(this).scrollTop();
  });
});

"working" fiddle (hash wont change on fiddle)

加入:

如果您只想查看网址更改:

$(function () {
  var currentHash = "#";
  var blocksArr = $('.block');

  $(document).scroll(function () {
     var currentTop = window.pageYOffset/1;
     for (var i=0; blocksArr.length; i++){
         var currentElementTop = $(blocksArr[i]).offset().top;
         var hash = $(blocksArr[i]).attr('id');
         if (currentElementTop < currentTop && currentTop < currentElementTop + $(blocksArr[i]).height() && currentHash!=hash){
                if(history.pushState) {
                history.pushState(null, null, '#'+hash);
        }
        else {
            location.hash = '#'+hash;
        }
                currentHash = hash;
         }

     }

  });
});