history.pushState跨域
history.replaceState瀏覽器
<ul> <li><a href="?name=red">A</a></li> <li><a href="?name=blue">B</a></li> <li><a href="?name=green">C</a></li> </ul> <div style='width: 100px; height: 100px;'></div> <script> function setBackgroundColor(color) { document.querySelector('div').style.backgroundColor = color; } /** * [color description] * @type {String} * 1. data 參數 * 2. title * 3. url */ // 將頁面替換成當前url的頁面 history.replaceState({ color: 'red' }, '當前爲A頁面', "?name=a"); setBackgroundColor("red"); // 瀏覽器前進後退就會觸發popstate事件, 經過事件的 state 能夠得到參數值 window.onpopstate = function (event) { // console.log(event.state); setBackgroundColor(event.state.color); } let aObj = document.querySelectorAll('a'); aObj.forEach((item) => { item.addEventListener('click', function(event) { event.preventDefault(); // 請求地址 let query = this.href.split('?')[1]; // 請求的參數值 let color = query.split('=')[1]; // history.state:獲取歷史棧中最頂端的state數據(即history.pushState中的第一個參數) if(history.state.color !== color) { setBackgroundColor(color); // 放入歷史記錄中 history.pushState({color: color},color, location.href.split('?')[0] + '?' + query); } }) }) </script>