有一个需求要拦截移动端返回键. 使用js拦截物理返回键事件我认为不可取.可以在导航做一些手脚
下面说两个知识点
- 锚点:命名锚记像一个迅速定位器一样是一种页面内的超级链接
- popstate事件 :当活动历史记录条目更改时,将触发popstate事件
原理也比较简单更改锚点history堆栈会发生变化,并且页面不会刷新.
下面是代码
- test.html
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width">
<script type="text/javascript">
function testClicker(){
location.href = './test2.html'
}
</script>
<body>
<button onclick="testClicker()">跳转test2</button>
</body>
</html>
- test2.html
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width">
<script type="text/javascript">
var count = 0 ;
window.history.pushState(null, null, "#");
window.addEventListener("popstate", function(e) {
console.log("-------------popstate---");
window.history.pushState(null, null, "#");
document.getElementById('logView').innerHTML = "用户点击返回" + (++count)
})
</script>
<body>
<p id="logView">test2</p>
</body>
</html>