You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript实现DIV元素display属性的切换?代码问题求助

Fixing Your DIV Toggle Issue

First off, let's spot the main bug in your code—you're using a single equals sign (=) in your if condition instead of a comparison operator like ===. That's not checking if the display is "block"—it's setting it to "block" every time, then immediately switching it to "none". No wonder your toggle isn't working!

Let's break down the fixes step by step:

1. Fix the Comparison Operator

Replace = with === to actually compare the display value instead of assigning it. But even that's not enough for the initial state, here's why:

Your CSS sets div#hidden { display:none; }, but the obj.style.display property only reads inline styles (styles set directly on the element via the style attribute). When the page loads, your element doesn't have an inline style attribute, so obj.style.display will be an empty string (""), not "none".

2. Robust Toggle Logic

To handle both the initial hidden state (from CSS) and subsequent toggles, you can use one of these reliable approaches:

Option A: Check for empty string or "none"

This accounts for the initial state where inline style isn't set:

let menu = function() {
  var obj = document.getElementById("hidden");
  // If it's hidden (either via CSS or inline style)
  if (obj.style.display === "none" || obj.style.display === "") {
    obj.style.display = "block";
  } else {
    obj.style.display = "none";
  }
};

Option B: Use Computed Style (Most Reliable)

This gets the actual current display style, regardless of whether it's set in CSS or inline:

let menu = function() {
  var obj = document.getElementById("hidden");
  const currentDisplay = window.getComputedStyle(obj).display;
  obj.style.display = currentDisplay === "block" ? "none" : "block";
};

3. Minor HTML Cleanup

Your anchor tag has a missing space between the href and id attributes—while it might work, it's better to format it properly for readability:

<a href="javascript:menu()" id="info"> INFO </a>
<div id="hidden"> <!-- some stuff --> </div>

Bonus: Modern Approach (Using classList)

If you're open to a cleaner, more maintainable method, use classList.toggle() instead of manipulating the display property directly. This keeps all styling in CSS:

Update your CSS to add a hidden class:

div#hidden {
  display: block;
}
div#hidden.hidden {
  display: none;
}

Then your JavaScript becomes much simpler:

let menu = function() {
  document.getElementById("hidden").classList.toggle("hidden");
};

This way, you can easily add transitions or adjust styling later without touching your JS code.

内容的提问来源于stack exchange,提问作者WEEFA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:53:01