Change url when manually scrolled to an id even scrolling to top?

前端 未结 1 1699
不知归路
不知归路 2020-12-21 11:14

Is it possible to change the URL in the address bar instantly when I scroll to an id? Or have a long document with multiple id and the url changes on address bar, when I hit

相关标签:
1条回答
  • 2020-12-21 11:34

    After your comment, I understand what you are trying to achieve:

    The following code is based on scroll up/ down.

    Will store the current block and make you "jump" between blocks:

    $(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)

    added:

    If you only want to see the URL changes:

    $(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;
             }
    
         }
    
      });
    });
    
    0 讨论(0)
提交回复
热议问题