当Div进入视图时,pushState

pushState when Div comes in to view

本文关键字:pushState 视图 Div      更新时间:2023-09-26

我目前正在开发一个单页应用程序,并使用jQuery路点浏览页面。不过,当手动滚动时,我希望在div进入视图时使用pushState来更改地址栏中的url。我该怎么做呢?谢谢

您想根据页面滚动来更改url吗?url中唯一可以更改的部分是"hash",例如http://example.com/index.html#div5
为此,您需要检测页面滚动,然后设置此哈希字符串。

$(window).scroll(function () {
    //this shows how many pixels we have scrolled
    var scroll = window.scrollTop;
    //now we loop through the divs
    $('.div').each(function(){
        var top = $(this).offset().top,
           width = $(this).width();
        //if we are seing the current div, set the url and...
        if(scroll >= top && scroll <= top + width) {
            location.hash = $(this).attr('id');
            return false;// ... and stop looping through the divs
        }
    });
});

我想你的html是这样的:

<div class="div" id="this is the url for the first div">
</div>
<div class="div" id="this is the url for the second div">
</div>
<div class="div" id="this is the url for the third div">
</div>

只需收听文档滚动

$(window).on('scroll'/*, your handler */);

并计算div相对于视图端口的位置,很好的解决方案是:

https://stackoverflow.com/a/125106/990942

基本上,你需要

var myBlocks = $('.div-you-track') // gather all your blocks
function resolve() {
    var resolved;
    myBlocks.each(function(block) {
        if (inViewort(block)) { // for inViewport look link above
            resolved = block;
        }
    });
    if (resolved) {
        // push your state
        // you can use data-* attributes to determine link, for example
        // resolved.data('url')
    }
}
$(window).on('scroll', resolve); // listen to body

这是HTML示例

<div class="div-you-track"></div>
<div class="div-you-track"></div>
<div class="div-you-track"></div>
...