Knowledge Points:
1, Onpopstate event, Click the Back button (or call the method in JavaScript history.back()
) when triggered;
2, hash attribute: can be the anchor part of the URL (from the beginning of the #) operation (readable and writable);
About hash link Click to open link
Demand:
Page, when the current page click somewhere, pop up a layer covering the entire phone screen, pop this layer, click the Back button of the screen, hide the pop-up layer, and not exit the current page!
Solution:
When the Click event occurs, use the hash attribute to add an anchor point to the URL, show the popup layer, and click the Back button, remove the URL anchor point, hide the popup layer; Click the Back button to trigger onpopstate event; Why do I have to add an anchor point to the URL? All operations of the requirements description are on the same page, so if you do not add an anchor point to the URL, click on the show pop-up layer and the user clicks the Back button to exit the current page!
$ (". Btn"). Click (function () { Location.hash = "Win";//To add an anchor to the URL, this anchor is automatically loaded to the URL of $ (". Window"). Show (); $ ("#search"). focus ();});
Checklocation Method detects if there is an anchor on the URL win, there is an anchor point to show the pop-up layer, conversely, the hidden pop-up layer
The function checklocation () { //hash property is a readable, writable string that is the anchor part of the URL (the part that begins with the # number). if (location.hash.indexOf ("#win") >-1) { $ (". Window"). Show (); } else{ $ (". Window"). Hide (); }}
The Popstate event is triggered when the browser is operating, such as clicking the Back button (or calling the History.back () method in JavaScript). Window.onpopstate = function () { checklocation ();};
A rough Demo
Onpopstate event triggered when the browser clicks the rewind button