如何使我的箭头手风琴在被按下时显示一个向下指的箭头?

3

我创建了一个带有一个指向右侧的箭头的手风琴,当单击它时,我希望箭头指向下方。我该如何实现这个功能?我应该使用图像代替普通箭头,还是可以像我现在使用的那样使用箭头?以下是我的jsfiddle代码:https://jsfiddle.net/homjt76L/2/

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.nextElementSibling;
    if (content.style.maxHeight){
      content.style.maxHeight = null;
    } else {
      content.style.maxHeight = content.scrollHeight + "px";
    } 
  });
}
h1 {
    text-align: center;
}

.arrow {
    border: solid black;
    border-width: 0 3px 3px 0;
    display: inline-block;
    padding: 3px;
}

.down {
    margin-right: 50px;
    float: left;
    transform: rotate(45deg);
    -webkit-transform: rotate(45);
}

.right {
    margin-right: 50px;
    float: left;
    transform: rotate(-45deg);
    -webkit-transform: rotate(-45deg);
}

.collapsible {
  color: black;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: solid thin;
  text-align: left;
  outline: none;
  font-size: 15px;
}

.active, .collapsible:hover {
  background-color: #555;
}

.collapsible:after {
  color: white;
  font-weight: bold;
  float: right;
  margin-left: 5px;
}

.active:after {
}

.content {
  padding: 0 18px;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
  background-color: #f1f1f1;
}
<h1>FAQ</h1>

<button class="collapsible" data-toggle="">
<b>Questions and Answers</b><i class="arrow right"></i>
</button>
<div class="content">
  <p>Lorem Ipsum...</p>
</div>


首先,您需要为箭头创建单独的按钮,然后当单击该按钮时,您可以将其旋转45度。 - user14466490
3个回答

2

我可能会将right类重命名为indicator,然后只需添加此内容。

.collapsible.active .indicator{
  transform: rotate(45deg);
}

这意味着你可以删除你已经编写的down类。如果你想要添加一个小的过渡效果,indicator类将会是这样的。
.indicator {
    margin-right: 50px;
    float: left;
    transform: rotate(-45deg);
    transition: 0.2s ease transform;
}

谢谢,这对我有帮助。 - Keenonthedaywalker

2

在className改变时,将图标的className从“right”改为“down”。

请查看这里:https://jsfiddle.net/Dev024/t4fe6quL/2/

if(this.classList.contains("active"))
{
    this.childNodes[1].className = "arrow right"
}
else
{
    this.childNodes[1].className = "arrow down"
}

我使用了上面的答案,但无论如何还是感谢您的帮助。 - Keenonthedaywalker

1
您可以像这样放置CSS:

.collapsible.active .right:{
    transform: rotate(45deg);
    -webkit-transform: rotate(45deg);
 }

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