Html5拦截Android返回键方法

有一个需求要拦截移动端返回键. 使用js拦截物理返回键事件我认为不可取.可以在导航做一些手脚

下面说两个知识点

  • 锚点:命名锚记像一个迅速定位器一样是一种页面内的超级链接
  • popstate事件 :当活动历史记录条目更改时,将触发popstate事件

原理也比较简单更改锚点history堆栈会发生变化,并且页面不会刷新.

下面是代码

  1. 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>
  1. 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>

转载于:https://my.oschina.net/xtdhwl/blog/1068692

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值