zoukankan      html  css  js  c++  java
  • 利用popstate事件和window下的history对象处理浏览器跳转问题

    History 接口
    属性
    History.length 表示历史会话中元素的数目
    History.scrollRestoration 允许Web应用程序在历史导航上显式地设置默认滚动恢复行为。此属性可以是自动的(auto)或者手动的(manual)。
    History.state 返回一个表示历史堆栈顶部的状态的值。这是一种可以不必等待popstate 事件而查看状态而的方式。
    方法
    History.back()
    等同于history.go(-1)

    History.forward()
    等同于historygo(1)

    History.go()
    这个方法中如果参数超出范围或者不对就不会起效果

    History.pushState()
    pushState() 带有三个参数:一个状态对象,一个标题(现在被忽略了),以及一个可选的URL地址。下面将对这三个参数进行细致的检查

    function pushHistory() {  
      var state = {  
        title: "title",  
        url: "#"  
      };  
      window.history.pushState(state, "title", "#xx");  
     } 
    

    监听浏览器返回按钮

    function pushHistory() {  
        var state = {  
          title: "title",  
          url: "#"  
        };  
        window.history.pushState(state, "title", "#xx");  
    }
    pushHistory();
    window.addEventListener("popstate", function(e) {  
        console.log(e);
        alert("我监听到了浏览器的返回按钮事件啦");//根据自己的需求实现自己的功能  
    }, false);
    

    禁止返回上一页的一种方案

    history.pushState(null, null, document.URL);
    window.addEventListener("popstate",function(e) {  
        console.log(e);
        history.pushState(null, null, document.URL);
    }, false);
    

    这个其实就是利用pushState向浏览历史列表中插入当前页面,在点击后退前和点击时都插入一次,那样无论点前进还是后退永远都会留在这个页面了
    JS监听浏览器前进后退事件

    
    window.addEventListener('popstate', function(e) {
      init++
      if (init < 2) {
        router.beforeEach((to, from, next) => {
          let arr1 = to.path.split('/')
          console.log('aaaa...1111',arr1)
          let arr2 = from.path.split('/')
          console.log('bbbbb....22222',arr2)
          if (arr1.length === 2) {
            
            if (arr1[1].length === 0) {
              arr1.splice(1, 1)
              console.log('ccccc',arr1)
            }
          }
          if (arr2.length === 2) {
            if (arr2[1].length === 0) {
              arr2.splice(1, 1)
            }
          }
          if (arr1.length < arr2.length) {
            router.toGoBack()
          } else {
            router.toGoIn()
          }
          next()
        })
      }
    }, false)
    


    本文部分转载自:https://www.cnblogs.com/wancheng7/p/8542544.html

  • 相关阅读:
    大数据并发控制思考
    同步和异步的区别
    java枚举使用详解
    利用反射实现动态方法调用
    利用反射查看类的声明信息
    用两个栈实现对列
    c标签 if else c标签 总结
    struts2标签获取parameter,request,session,application中的值
    mysql日期加减
    详细介绍Java中的堆、栈和常量池
  • 原文地址:https://www.cnblogs.com/smart-girl/p/13030760.html
Copyright © 2011-2022 走看看