小编典典
我所做的是将对象文字传递给pushState()页面加载。这样,您始终可以返回到第一个创建的pushState。就我而言,我不得不两次推后才可以返回。推动页面加载状态帮助了我。
HTML5允许您使用数据属性,因此对于触发器,您可以使用它们来绑定HTML数据。
我之所以使用try catch,是因为我没有时间为较旧的浏览器找到一个polyfill。您可能需要检查Modernizr,如果您的情况需要这样做。
页面加载
try {
window.history.pushState({
url: '',
id: this.content.data("id"), // html data-id
label: this.content.data("label") // html data-label
}, "just content or your label variable", window.location.href);
} catch (e) {
console.log(e);
}
活动扶手
填充了默认信息的对象
var obj = {
url: settings.assetsPath, // this came from php
lang: settings.language, // this came from php
historyData: {}
};
绑定history.pushState()触发器。在我的情况下是一个委托,因为我在页面上有动态元素。
// click a trigger -> push state
this.root.on("click", ".cssSelector", function (ev) {
var path = [],
urlChunk = document.location.pathname; // to follow your example
// some data-attributes you need? like id or label
// override obj.historyData
obj.historyData.id = $(ev.currentTarget).data("id");
// create a relative path for security reasons
path.push("..", obj.lang, label, urlChunk);
path = path.join("/");
// attempt to push a state
try {
window.history.pushState(obj.historyData, label, path);
this.back.fadeIn();
this.showContent(obj.historyData.id);
} catch (e) {
console.log(e);
}
});
将history.back()事件绑定到自定义按钮,链接或其他内容。我使用了,.preventDefault()因为我的按钮是链接。
// click back arrow -> history
this.back.on("click", function (ev) {
ev.preventDefault();
window.history.back();
});
当历史记录弹出时->检查推送状态,除非是第一次尝试
$(window).on("popstate", function (ev) {
var originalState = ev.originalEvent.state || obj.historyData;
if (!originalState) {
// no history, hide the back button or something
this.back.fadeOut();
return;
} else {
// do something
this.showContent(obj.historyData.id);
}
});
使用对象文字作为参数很容易传递您的ID。然后,您可以使用一个功能showContent(id)。
无论我在哪里使用this它,都不过是存储在IIFE中的jQuery对象/函数。
请注意,我将这些脚本与实现结合在一起,并结合了您最初的要求。所以希望这会给您一些新的想法;)
2020-07-26