如何在到达特定div时更改URL并使用PushState在div中显示更改的url的内容

时间:2019-01-27 19:33:39

标签: pushstate

我正在尝试编写代码,将其向下滚动到特定的div,然后更改网址,并在该特定的div内显示该URL的内容,依此类推。类似于获取rss feed并将其显示在首页中,但要使用pushstate进行。

    <script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js'></script>
    
    <script type="text/javascript">
        jQuery(function ($) {
        $('#page0').load('https://example.com/hr-pillar-post');
        $('#page1').load('https://example.com/hr-pillar-post/how-do-i-become-a-hr-professional');
    	$('#page2').load('https://example.com/hr-pillar-post/what-can-i-do-with-a-degree-in-hr');
        });
    </script>
    <script>
    function isScrolledIntoView(elem)
    {
        var $elem = $(elem);
        var $window = $(window);
    
        var docViewTop = $window.scrollTop();
        var docViewBottom = docViewTop + $window.height();
    
        var elemTop = $elem.offset().top;
        var elemBottom = elemTop + $elem.height();
    
        return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
    }
    
    $(window).scroll(function() {
        if (isScrolledIntoView("#page0")) { window.history.pushState("state", "title", "/hr-pillar-post"); document.title = "HR Pillar Page"; return; }
        if (isScrolledIntoView("#page1")) { window.history.pushState("state", "title", "/hr-pillar-post/how-do-i-become-a-hr-professional"); document.title = "How do i become a HR professional"; return;}    
        if (isScrolledIntoView("#page2")) { window.history.pushState("state", "title", "/hr-pillar-post/what-can-i-do-with-a-degree-in-hr"); document.title = "What can i do with a degree in HR?"; return; }
    });
    </script>
    <div id="page0"></div>
    <hr>
    <div id="page1"></div>
    <hr>
    <div id="page2"></div> 

0 个答案:

没有答案