问题
I've been trying to have a div 'footer' stay at the bottom of the page, and stay open through page changes. I have achieved this by using JQuery's .load function on a main content div, however, using that method, when someone goes to a different page, the URL stays the same. Is there a way to keep the links changing the URL, but keep the div open? I plan on playing music through said div, so it can't close between page switches, or the music will stop/have to rebuffer.
回答1:
You can do this with HTML5 using:
window.history.pushState(obj, "Title", url);
after your .load()
call.
It'll change the displayed URL to match the one in the call, but only URLs that belong to the same domain are permitted.
See https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history
回答2:
You'll have to use frames and hash urls if you want to support non-HTML5 browsers. I'd use an old-fashioned frameset. (I can't believe I'm actually suggesting a frameset. It's considered bad practice, and I haven't written code like this in probably 11 years, but in this case, it actually seems like the right solution. You could use iframes, but I think a frameset actually makes more sense.)
<frameset border="0" rows="*,100">
<frame src="/mainPage" id="content" />
<frame src="/footer" id="footer" />
</frameset>
Use Ben Alman's hashchange plugin, and use a script like this to manage the page navigation:
$(function () {
$("frame").load(function () {
document.title = w.document.title;
var links = $("a[href]", this.contentWindow.document);
links.attr("target", "_top");
links.click(function (e) {
if (this.hostname == location.hostname) {
e.preventDefault();
var path = this.pathname.replace(/^[^\/]/, "$&/");
location.hash = "#" + path + this.search + this.hash;
}
});
});
var w = $("#content")[0].contentWindow;
$(window).hashchange(function () {
var hash = location.hash.substr(1) || "/mainPage";
var contentLoc = w.location.pathname + w.location.search + w.location.hash;
if (hash.toLowerCase() != contentLoc.toLowerCase()) {
w.location.replace(hash);
}
}).trigger("hashchange");
});
Demo: http://jumpingfishes.com/framed/
As an alternative to frames, you could use AJAX to reload the content, but frames may be quicker to implement.
来源:https://stackoverflow.com/questions/8565211/keep-div-open-through-page-changes