我目前正在开发一个单页应用程序,并在页面周围使用jQuery waypoints。当手动滚动时,我想在div进入查看时在地址栏中使用pushState to change the url。我怎么能这样做呢?谢谢!
答案 0 :(得分:0)
您想根据页面滚动更改网址吗?可以更改的网址的唯一部分是'哈希',例如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>
答案 1 :(得分:-1)
只是听取文档滚动
$(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>
...