当Div进入视图时,pushState
pushState when Div comes in to view
我目前正在开发一个单页应用程序,并使用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>
...
相关文章:
- 如何使用javascript从主svg对象动态创建svg视图框
- 正在使用$location.path(.)路由ng视图
- angular.js没有'无法在PhoneGap中处理视图标记
- 如何包含特定于每个视图angularjs的javascript文件
- 通过在Dojo mobile ViewController.openExternalView中动态更改打开同一外部视图的
- Kendo:我该如何在树视图中创建一个递归的hieiarchy
- Ajax Live搜索发布到Laravel视图
- backbone.js无法渲染视图
- 根据某些条件在视图之间切换
- ng视图外的链接重定向到ng视图内的页面
- 如何在Jquery中发布后将值从视图返回到控制器
- 将日期时间作为 JSON 发送将无法在我的视图中正确显示
- 使用Scala Play Framework视图中的键检索映射值
- FF视图源|脚本高亮显示为红色
- 如何使bxslider仅在移动视图中处于活动状态
- 为什么不't我的变量在我的控制器中填充后在我的视图中呈现
- 在不破坏未定义函数的情况下,对多个视图使用单个js文件
- 在Rails中更新Div,而不更改更新请求后的视图
- 如何在Ionic Android中将Javascript注入到web视图中
- 当Div进入视图时,pushState