頁面鏈接跳轉歷史URL不記錄的兼容處理


1.阻止跳轉a標簽的鏈接

2.location.replace(href) 不生成新的歷史記錄, 但有bug

3.首先通過HTML5 history.replaceState()方法把當前URL地址替換成以個井號#結尾的目前鏈接地址;

4.執行location.replace('')刷新當前地址(此時#會忽略);

(function(){
    var fnUrlReplace = function (eleLink) {
        if (!eleLink) {
            return;
        }
        var href = eleLink.href;
        if (href && /^#|javasc/.test(href) === false) {
            if (history.replaceState) {
                // 生成新的URL
                history.replaceState(null, document.title, href.split('#')[0] + '#');
                location.replace('');       // 刷新當前頁面URL
            } else {
                location.replace(href);     // 不生成新的歷史記錄
            }
        }
    };

    document.getElementsByTagName('a')[0].onclick = function (event) {
        // 阻止跳轉
        if (event && event.preventDefault) {
            event.preventDefault();     
        }
        fnUrlReplace(this);
        return false;
    };
}());

參考: http://www.zhangxinxu.com/wordpress/2017/02/page-link-url-history-null-not-record/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM