zoukankan      html  css  js  c++  java
  • 监听浏览器返回键、后退、上一页事件(popstate)操作返回键

      在WebApp或浏览器中,会有点击返回、后退、上一页等按钮实现自己的关闭页面、调整到指定页面、确认离开页面或执行一些其它操作的需求。可以使用 popstate 事件进行监听返回、后退、上一页操作。

      一、简单介绍 history 中的操作

        1.window.history.back(),后退

        2.window.history.forward(),前进

        3.window.history.go(num),前进或后退指定数量历史记录

        4.window.history.pushState(state, title, utl),在页面中创建一个 history 实体。直接添加到历史记录中。

          参数:  state:存储一个对象,可以添加相关信息,可以使用 history.state 读取其中的内容。

               title:历史记录的标题。

               url:创建的历史记录的链接。进行历史记录操作时会跳转到该链接。

        5.window.history.replaceState(),修改当前的 history 实体。

        6.popstate 事件,history 实体改变时触发的事件。

        7.window.history.state,会获得 history 实体中的 state 对象。

      二、使用方法

        取消默认的返回操作:

        1.添加一条 history 实体作为替代原来的 history 实体

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

        2.监听 popstate 事件

    window.addEventListener("popstate", function(){
        //doSomething
    }, false)

      三、注意事项

        1.每次返回都会消耗一个 history 实体,若用户选择取消离开,则需要继续 pushState 一个实体

        2.pushState 只能一个实体,多个实体返回会出错。使用 window.history.state 查询是否存在添加的实体。

        

        

  • 相关阅读:
    mysql存储过程笔记
    mysql 命令行操作
    第一天前来报到
    Android Studio导入工程版本问题、gradle版本问题
    LogUtils-定制自己的日志工具
    Git2.11安装下载和github使用
    Android Studio 2.3版本 以及相应的gradle3.3包
    android 导入第三方jar包和类库
    GifView——Android显示GIF动画
    Android中dip、dp、sp、pt和px的区别详解
  • 原文地址:https://www.cnblogs.com/Easty/p/7820055.html
Copyright © 2011-2022 走看看