gpt4 book ai didi

javascript - 使一个面板在另一个面板打开时关闭

转载 作者:行者123 更新时间:2023-11-27 23:16:41 25 4
gpt4 key购买 nike

我想做的是,如果其中一个面板打开,它会在您单击另一个面板时关闭。 我查看了一些与我的类似的其他问题,但它们似乎都对面板使用了不同的方法。

这是它的 fiddle :https://jsfiddle.net/3q87y2u8/

这是 JS:

    var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
acc[i].onclick = function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.maxHeight){
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
}
}

我还想让“+”在悬停时改变颜色。有点像目前的文字。不过,我似乎无法在 CSS 中直接调用它。

谢谢!

最佳答案

您可以获取当前处于事件状态的元素,然后像这样删除事件类:

// Is an array of elements matching the selector
var active = document.getElementsByClassName('active');

// If there are any matching elements and it is not the same one that has just been clicked on
if (active.length && active[0] !== this) {
active[0].classList.remove('active');
}

一方评论(您当然可以随意忽略!):对于最大高度,您不需要计算出高度(当然除非它干扰了您已经设置的页面结构)。您可以只使用一些较大的高度,因为它是您设置的最大高度,而不是它会自动达到其自然高度的高度。您也可以只使用 CSS 实现这一点,包括动画,下面还包括更新加号上的悬停文本。

// Set regular state height to 0 and add a transition effect
.panel {
max-height: 0px;
transition: max-height .25s ease;
}

// For whatever button is active find the adjacent panel and set its max height and a transition effect
.active + .panel {
max-height: 250px;
transition: max-height .25s ease;
}

// Here is where you change the color of the active and hovered plus/minus sign
button.accordion.active:after,
button.accordion:hover:after {
color: red;
}

https://jsfiddle.net/xz2mpzg2/1/ https://jsfiddle.net/xz2mpzg2/2/

关于javascript - 使一个面板在另一个面板打开时关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42743555/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com