Javascript 手风琴

Javascript Accordian

我有一个简单的手风琴工作,除了一件事。我希望能够再次重新单击相同的手风琴项目,并能够将高度设置为“0”。

目前,当我单击不同的手风琴项目时,打开的手风琴项目会关闭,这正是我想要做的 — 但我 想要能够重新单击打开手风琴项目并在单击时关闭该项目。请参阅下面的工作示例:

https://codepen.io/celli/pen/BaNLJWb

// set heights to 0
gsap.set('.content', {
  height: 0
});

// click function
$('.accordianItem').click(function() {

  if ($('.accordianItem').hasClass('on')) {
    gsap.to($('.content'), {
      duration: .25,
      height: 0
    });
    $('.accordianItem').removeClass('on');
  }

  gsap.to($(this).children('.content'), {
    duration: .25,
    height: "auto"
  });
  $(this).addClass('on');
});

我可以添加什么代码来添加这个额外的功能?

我修改了你的代码,添加了另一个 if 来检查点击的元素是否已经 'on' class。它现在应该可以按预期工作(当用户单击已打开的 header 时隐藏)。

// set heights to 0
gsap.set('.content', {height:0});

// click function
$('.accordianItem').click(function() {
    if($(this).hasClass("on")){
       gsap.to($('.content'), {duration:.25, height:0});
       $('.accordianItem').removeClass('on');
    }
    else{
      if ($('.accordianItem').hasClass('on')) {
         gsap.to($('.content'), {duration:.25, height:0});
         $('.accordianItem').removeClass('on');
      }
      gsap.to($(this).children('.content'), {duration:.25, height:"auto"});
      $(this).addClass('on');
    }

});

你可以比你现在做的更简单:

// Create the animation that you need
const tl = gsap.timeline({paused: true});
tl.to('.content', {duration: 0.25, height:0});

// Set the timeline to its end state
tl.progress(1);

// Toggle the timeline's direction
$('.accordianItem').click(function() {
    tl.reversed() ? tl.play() : tl.reverse();
});

Demo

我强烈建议您查看 the GreenSock forums。它们非常有用,您可以从 GSAP 和网络动画专家那里获得快速帮助:)