简体   繁体   中英

How can I use the browser back button for closing an overlay?

I read this article: JavaScript or jQuery browser back button click detector

And tried all of the examples there to use the browser back button to hide an overlay.

This is the best working try:

 $("button").click(function() { $("#overlay").css("display", "block"); }); window.onpopstate = function() { $("#overlay").css("display", "none"); }; history.pushState({}, '');
 * { font-family: sans-serif; margin: 0; padding: 0; } html, body { width: 100%; height: 100%; } #overlay { position: fixed; top: 0; left: 0; display: none; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.8); color: white; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="text">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</div> <button>Click me</button> <div id="overlay">Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. </div>

If you click the button , and then use the browser back button, the overlay fades out. That's how I expect it. But: It works only once, for whatever reason. Why? How can I let it work for every case?

I would be very thankful for help!

You need to use pushState every time the popup is opened:

$("button").click(function() {
  history.pushState({}, '');
  $("#overlay").css("display", "block");
});


window.onpopstate = function() {
  $("#overlay").css("display", "none");
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM