使用按钮切换显示/隐藏div?

84

希望这是一个简单的问题。我有一个 div,我想用一个按钮来切换它的隐藏/显示。

<div id="newpost">
8个回答

144

纯JavaScript:

var button = document.getElementById('button'); // Assumes element with id='button'

button.onclick = function() {
    var div = document.getElementById('newpost');
    if (div.style.display !== 'none') {
        div.style.display = 'none';
    }
    else {
        div.style.display = 'block';
    }
};

查看演示

jQuery:

$("#button").click(function() { 
    // assumes element with id='button'
    $("#newpost").toggle();
});

查看演示


你好,有没有想法如何使它在漂亮的淡入淡出中切换? - Aerodynamika
1
@deemeetree:你可以将'slow'传递给toggle。如果你正在使用纯JS解决方案,请让我知道,我可以想出一些解决方法。 - Andrew Whitaker
谢谢,@Andrew。我也发现在新的jQuery中有fadeToggle函数。 - Aerodynamika
1
我正在查看其他问题,意外在这个线程(http://stackoverflow.com/questions/18808112/jquery-toggle-function-not-working)中找到了一个答案... 显然这是因为新版本的 JQuery 不再支持 toggle 功能。 - Barry Michael Doyle
1
@BarryDoyle: 实际上,toggle-event在1.8版本中已被弃用。这个答案中使用toggle的方式仍然可用,可以查看这个示例:http://jsfiddle.net/KpFRb/532/ - Andrew Whitaker
显示剩余4条评论

68

请参考jQuery Toggle

HTML:

<div id='content'>Hello World</div>
<input type='button' id='hideshow' value='hide/show'>

jQuery:

jQuery(document).ready(function(){
    jQuery('#hideshow').live('click', function(event) {        
         jQuery('#content').toggle('show');
    });
});

对于 jQuery 1.7 及更高版本,请使用:

jQuery(document).ready(function(){
    jQuery('#hideshow').on('click', function(event) {        
        jQuery('#content').toggle('show');
    });
});

供参考,请查看此演示


1
现在 .live() 在 1.7 版本中已被弃用,并在 1.9 版本中被移除,因此在新版本中您可以使用 .on()(详情请参见 https://api.jquery.com/on/)。 - Rohit Dubey
你怎么设置默认隐藏?编辑:我已经想到了,就在捕捉按钮推送的代码之前添加切换。 - simonr2
不使用jQuery怎么样?每个人都可以用jQ完成它。 - Green
2
我认为 toggle('show') 是一个笔误(一些人肆无忌惮地复制并粘贴到其他答案中),因为只有 'slow''fast' 是被接受的持续时间字符串。尽管如此,它仍然可以工作,因为我认为任何无效的字符串都将默认为 'slow'。https://jsfiddle.net/d5y06e6o/ - Shikkediel
@simonr2你能详细说明一下你是如何使其默认隐藏的吗? - petebocken

41

使用 style 进行切换的方式如下:

myElement.style.display = someBoolState ? "block" : "none"  

这是一个非常糟糕的想法,以下是一些在JS、jQuery、HTML、CSS中的示例:

JavaScript .classList.toggle()

const elToggle  = document.querySelector("#toggle");
const elContent = document.querySelector("#content");

elToggle.addEventListener("click", function() {
  elContent.classList.toggle("is-hidden");
});
.is-hidden {
  display: none;
}
<button id="toggle">TOGGLE</button>
<div id="content" class="is-hidden">Some content...</div>

以上的美妙之处在于样式仅在您的样式表中处理,通过删除.is-hidden类,您的元素将恢复其原始的display模式,无论是blocktableflex还是其他什么。

jQuery .toggle()

.toggle()文档
.fadeToggle()文档
.slideToggle()文档

$("#toggle").on("click", function(){
  $("#content").toggle();                 // .fadeToggle() // .slideToggle()
});
#content{
  display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>

jQuery - Toggle .toggleClass()文档

.toggle() 方法切换一个元素的 display 属性值为"block"/"none"

$("#toggle").on("click", function(){
  $("#content").toggleClass("show");
});
#content{
  display:none;
}
#content.show{
  display:block; /* P.S: Use `!important` if missing `#content` (selector specificity). */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>

HTML5 - 使用<summary><details>进行切换

(不支持IE和Opera Mini)

<details>
  <summary>TOGGLE</summary>
  <p>Some content...</p>
</details>

HTML - 使用checkbox切换

[id^=toggle],
[id^=toggle] + *{
  display:none;
}
[id^=toggle]:checked + *{
  display:block;
}
<label for="toggle-1">TOGGLE</label>

<input id="toggle-1" type="checkbox">
<div>Some content...</div>

HTML - 使用radio切换

[id^=switch],
[id^=switch] + *{
  display:none;
}
[id^=switch]:checked + *{
  display:block;
}
<label for="switch-1">SHOW 1</label>
<label for="switch-2">SHOW 2</label>

<input id="switch-1" type="radio" name="tog">
<div>1 Merol Muspi...</div>

<input id="switch-2" type="radio" name="tog">
<div>2 Lorem Ipsum...</div>

CSS - 使用:target来切换内容

(确保您已经掌握了这个技能)

[id^=switch] + *{
  display:none;
}
[id^=switch]:target + *{
  display:block;
}
<a href="#switch1">SHOW 1</a>
<a href="#switch2">SHOW 2</a>

<i id="switch1"></i>
<div>1 Merol Muspi ...</div>

<i id="switch2"></i>
<div>2 Lorem Ipsum...</div>


动画类过渡

如果你选择JS / jQuery的方法来切换className,你可以为你的元素添加动画过渡效果,这是一个基本的例子:

const elToggle  = document.querySelector("#toggle");
const elContent = document.querySelector("#content");

elToggle.addEventListener("click", () => {
  elContent.classList.toggle("is-hidden");
});
#content {
  display: inline-flex; /* or whatever */
  transition: 0.6s;
}

.is-hidden {
  position: relative;
  visibility: hidden;
  opacity: 0;
  transform: scale(0);
}
<button id="toggle">TOGGLE</button>
<div id="content" class="is-hidden">Some Togglable content...</div>


你不能使用过渡效果来隐藏 display: none 的元素。 - Green
@Green 不可以这样做。这就是动画示例的原因。 - Roko C. Buljan
尊敬的@Roko C. Buljan先生,您好!请问有没有办法在CSS中最初显示div - 使用:target切换来回?请帮帮我,我真的很需要。谢谢。 - bilalmohib
1
@ProgrammingHobby 如果你想要将“默认打开”的容器之一(使用:target切换方法)之一,只需将所需的哈希 ID 添加到页面URI中,例如: index.html#switch1 - 然后立即查看元素ID switch1 打开。如果需要,您还可以使用JS URL.hash操纵URL对象:https://developer.mozilla.org/en-US/docs/Web/API/URL/hash - Roko C. Buljan
@Roko C. Buljan非常感谢您,先生。祝您有美好的一天。您的答案非常棒,我已经在我的多个项目中使用了它。再次感谢您。 - bilalmohib

13

这里是使用纯JavaScript实现toggle的方法:

<script>
  var toggle = function() {
  var mydiv = document.getElementById('newpost');
  if (mydiv.style.display === 'block' || mydiv.style.display === '')
    mydiv.style.display = 'none';
  else
    mydiv.style.display = 'block'
  }
</script>

<div id="newpost">asdf</div>
<input type="button" value="btn" onclick="toggle();">

4
不错,这是一个简单易懂的JavaScript解决方案。我建议将输入类型更改为按钮而不是提交,因为提交会将表单发布... - Paul Sasik

1
尝试使用不透明度(opacity)。

div { transition: all 0.4s ease }
.hide { opacity: 0; }
<input onclick="newpost.classList.toggle('hide')" type="button" value="toggle">

<div id="newpost">Hello</div>


0

这是我使用类隐藏和显示内容的方法。将类更改为“nothing”将把显示更改为块,将类更改为“a”将显示内容。none。

<!DOCTYPE html>
<html>
<head>
<style>
body  {
  background-color:#777777;
  }
block1{
  display:block; background-color:black; color:white; padding:20px; margin:20px;
  }
block1.a{
  display:none; background-color:black; color:white; padding:20px; margin:20px;
  }
</style>
</head>
<body>
<button onclick="document.getElementById('ID').setAttribute('class', '');">Open</button>
<button onclick="document.getElementById('ID').setAttribute('class', 'a');">Close</button>
<block1 id="ID" class="a">
<p>Testing</p>
</block1>
</body>
</html>

0
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#hideshow').click(function(){
    $('#content').toggle('show');
  });
});
</script>

以及HTML

<div id='content'>Hello World</div>
<input type='button' id='hideshow' value='hide/show'>

-1
你可以使用以下的代码:
```javascript mydiv.style.display === 'block' = (mydiv.style.display === 'block' ? 'none' : 'block'); ```

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接