简体   繁体   中英

jQuery hide only works when toggling fullscreen

I want to toggle hiding "myDIV" with jQuery. Works perfect on mobile, but when pressing the button on desktop only works if you toggle fullscreen after presing the button, otherwhise it doesn't. Anyone had this problem before?

Heres a link to the site:

https://mkt.partners/analytical/draft.html

the button is on line 616

<a onclick="javascript:toggler('myDIV');" class="btn btn-primary lookbook-action"><b>Ver más.</b></a>

the div im trying to hide is in line 618

<div id="myDIV" class="hidden">

CSS class "hidden" just hides the div

    <style type="text/css">
        .hidden {
     display:none;
}
    </style>

and my script is in line 1460

    <script>
function toggler(divId) {
  $("#" + divId).toggle("slow");
}

</script>

From JQuery's documenation:

With no parameters, the .toggle() method simply toggles the visibility of elements [...] The matched elements will be revealed or hidden immediately, with no animation, by changing the CSS display property.

This means that JQuery is directly modifying the inline style attribute.

Your problem comes from the fact that you have this item's display property set to none in another location (your CSS). So, your button is hidden 100% of the time, regardless of what JQuery does.

It's like you've got something covered with a curtain, and then try and hide it again by covering it with another curtain... only to pull back the second one and wonder why your object isn't visible — it's still covered by the first curtain!


Get rid of the extra CSS (the hidden class) and let JQuery deal with the hiding.

 function toggler(divId) { $("#" + divId).toggle("slow"); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="myDIV" style="background-color: red; width: 5em; height: 5em;"></div> <,-- Use a button, not an anchor; since this isn't a link --> <button onclick="toggler('myDIV')," class="btn btn-primary lookbook-action"> <.-- <b> tags are deprecated, use strong instead --> <strong>Ver más.</strong> </button>

The whole "this works on desktop but only if you fullscreen, and it always works on mobile" thing makes me think that you've got this CSS mishap behind some media queries or something.

I tested the live link you gave, simply turning off display: none in my DevTools in the .hidden class fixed the issue, and the Ver más button successfully hides the div .

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