简体   繁体   中英

Jquery .toggle() and the browser back button

I have a fairly simple layout with a very strange outcome.

$(".main").on("hover", ".js_post", function () {
$(this).children('.js_del').toggle();
});

Essentially, when a user hovers over the .js_post div, the .js_del div is toggled. Here's the css that hides .js_del:

.js_del { display:none; }

Now, when the cursor hovers over .js_post, the .js_del div toggles, as expected. But, when the user clicks a link within the .js_post div and then clicks the browser back button, strange things happen...

In FF, all works as one would expect (ie, the browser interprets the click as a mouseleave and toggles the .js_del.)

In Safari, however, when the user clicks back, the browser applies toggle in reverse (ie, .js_del is showing and when the cursor hovers over .js_post, the .js_del link disappears.)

Even weirder...

I decide to add a handler to manually hide the .js_del div whenever an 'a' element within .js_post is clicked like this:

$(".js_post").find("a").click(function () {
    $(this).parents('.js_post').children('.js_del').hide();
});

And now, when viewed in Safari, all works as expected but in FF, it's reversed (ie, .js_del is showing and when the cursor hovers over .js_post, the .js_del link disappears)!

Any thoughts??? Thanks!

Because the back button is not making the page cacheing behave the same, and you can't be sure of the dom element state, toggle() calls can be rough. I split out the mouseenter and mouseleave instead of hover() , and specifically called out the visibility within the child selector. I also threw on a .hide() call at the very end to standardize the .js_del dom element visibility state regardless of back button browser issues.

js

$(".main").on({
  "mouseenter":function(evt){
    $(this).children('.js_del:hidden').toggle();
  },
  "mouseleave":function(evt){
    $(this).children('.js_del:visible').toggle();
  }
}, ".js_post", null).find('.js_del:visible').hide();

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