仅单击按钮即可折叠/关闭按钮

时间:2019-09-11 20:19:44

标签: javascript css

我正在尝试编写一个可响应的按钮,该按钮可以多次放置在同一行中,始终在包含该按钮的行下方显示其内容。

该代码段中有一个有效的代码,但它有一个小缺陷:由于使用了伪类focus,因此一旦打开按钮,就足以在屏幕上的任何位置单击以将其关闭。 / p>

按钮的通常行为是要关闭它,您必须单击它,所以是否也有可能对此按钮获得这种行为?

我使用了其他伪类,但没有成功,我猜想只有JavaScript可以完成这项工作。

.container {
  position: relative;
  margin: 2em;
}
.details {
  display: none;
}
.collapsible:focus {
    margin-bottom: 1.5em;
    pointer-events: none;
}
.collapsible:focus + .details 
{
  display: block;
  margin-top: -1.15em;
  position: absolute;
  left: 0;
  right: 0;
  background: yellow;
}
<div class=container>

You can <button class="collapsible">place</button><span class=details>yes</span> more than <button class="collapsible">one</button><span class=details>nice</span> per line, they are responsive and the content is always shown just <button class="collapsible">below</button><span class=details>cool</span> the line containing the button.
But once opened, you can close it with a click <button class="collapsible">everywhere</button><span class=details>not good</span> on the screen

</div>

进一步定制的Javascript

<script type="text/javascript">
var coll = document.getElementsByClassName("collapsible");
var i;

for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var content = this.parentElement.nextElementSibling;
    if (content.style.maxHeight){
      content.style.maxHeight = null;
    } else {
      content.style.maxHeight = content.scrollHeight + "px";
    } 
  });
}
</script>

1 个答案:

答案 0 :(得分:1)

这个想法的实现有点复杂,所以我就回答。

这是一个古老的技巧,将与隐藏的复选框相关联的标签用作点击目标。由于单击标签会选中或取消选中复选框,并且复选框的选中状态有一个伪类,因此我们可以使用它来保留样式的状态。将TylerH记入his answer来回答类似的问题Can I have an onclick effect in CSS?

我在这里是通过使用部分属性选择器实现的,因此在此示例中,所有复选框都必须具有以“ demo”开头的ID。复选框必须具有for的{​​{1}}属性的ID才能挂接。

label
.container {
  position: relative;
  margin: 2em;
}

.collapsible:focus {
  margin-bottom: 1.5em;
  pointer-events: none;
}


label {
  display: inline-block;
  background: lightgrey;
}

[id^="demo"] {
  display: none;
}

/* details that are next to labels that are next to unchecked checkboxes are hidden */
[id^="demo"]:not(:checked)+label+.details {
  display: none;
}


/* details that are next to labels that are next to checked checkboxes are displayed */
[id^="demo"]:checked+label+.details {
  display: block;
  position: absolute;
  left: 0;
  right: 0;
  background: yellow;
}

/* labels that are next to unchecked checkboxes have a different color 
   so you can track which ones are "on" */
[id^="demo"]:checked+label {
  background: blue;
  color: white;
}