HTML切换display属性失效:目标div无法显示问题求助
Hey there! Let's figure out why your toggle functionality isn't working as expected. The core issue is hiding in your CSS for #myDIV—you’ve set visibility: hidden;, which makes the element completely invisible regardless of its display value. Even when you manually change display to flex, the div stays hidden because this visibility setting overrides its visibility.
On top of that, your current toggle function only modifies the display property, so it never addresses the visibility rule that’s blocking your div from showing up.
Here are two straightforward fixes you can implement:
Fix 1: Remove the visibility property entirely
Since you’re already using display: none to hide the div initially, you don’t need the visibility: hidden; line at all. Just delete it from your #myDIV CSS rule. Your updated CSS will look like this:
#myDIV { position: fixed; left: 0; top: 50%; transform: translateY(-50%); width: 100%; text-align: center; align-items: center; justify-content: center; padding: 1%; /*background-color: lightblue;*/ flex-direction: row; font-family: Helvetica; display: none; }
Your existing toggle function will work perfectly with this change—clicking the third button will switch the div’s display between none and flex, showing/hiding it exactly as you intended.
Fix 2: Update your toggle function to handle visibility
If you want to keep using visibility: hidden for some reason, modify your JavaScript function to toggle both properties together:
function toggle() { var x = document.getElementById("myDIV"); if (x.style.display === "flex") { x.style.display = "none"; x.style.visibility = "hidden"; } else { x.style.display = "flex"; x.style.visibility = "visible"; } }
This way, every time you switch the display state, you also update the visibility to match, ensuring the div shows up when you want it to.
A quick side note: Since your initial display: none is set in external CSS, x.style.display will be empty the first time you run the function. That’s totally fine—it will still trigger the else branch and set display: flex (plus visibility: visible if you use Fix 2), which is exactly what you need.
内容的提问来源于stack exchange,提问作者student

