H5 应用返回按钮的js代码设计,设计思想模仿stack

本文介绍了一种用于H5应用的自定义返回逻辑实现方法,通过JavaScript代码改进了浏览器默认的history.back()功能,使其更适用于模拟手机应用的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

history.back();

这段代码有天然的缺陷,使用过的都知道,在H5的应用,特别是模仿手机应用的时候,这个不够用。

特写了一段js来实现类似的功能,如有重复和不喜请轻喷。大笑


不多说,上代码:

/**
 * Created by piggsoft@163.com on 2015/5/28.
 */
var historyUtils = {
    add : function (url) {
        var historyArray = historyUtils.getLocal();
        if (!historyArray) {
            historyArray = [];
        }
        var currentPage = historyArray.pop();
        if (currentPage && currentPage == url) {
            //do nothing
        } else if (currentPage){
            historyArray.push(currentPage); //历史里面没有现在传入的url,在加回去
        }
        historyArray.push(url);
        historyUtils.saveLocal(historyArray);
    },
    back : function() {
        var historyArray = historyUtils.getLocal();
        var currentPage = historyArray.pop();//去掉当前页面,pop取最后,类似stack
        var history = historyArray.pop();
        if (!history) {//没有历史页面
            historyUtils.add(currentPage);//将当前页面加入回数组中
            return;
        }
        historyUtils.saveLocal(historyArray);
        window.location.href = history;
    },
    getLocal : function() {
        var result = window.sessionStorage.getItem(historyUtils.key);
        if (!result) {
            return null;
        }
        return JSON.parse(result);
    },
    saveLocal : function(data) {
        window.sessionStorage.setItem(historyUtils.key, JSON.stringify(data));
    },
    init : function() {
        historyUtils.saveLocal([]);
    },
    key : "_history_"
}

historyUtils.add(window.location.href);


在需要实现back的地方调用

historyUtils.back();



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值