【问题标题】:Toggling a class on a Tailwind/Alpine.js accordion在 Tailwind/Alpine.js 手风琴上切换课程
【发布时间】:2021-12-07 19:13:28
【问题描述】:

我用 TailwindCSS 和 Alpine.js 创建了一个手风琴,它工作得很好,除了我还想更改按钮中的图标,当它被点击时展开内容。

这就是我所拥有的:

<div x-data="{selected:null,open:true}">

  <dl class="faqs mx-auto max-w-2xl">
    <dt>
      <span class="faq-q">Question</span>
      <button
        type="button"
        class="faq-toggle"
        @click="selected !== 1 ? selected = 1 : selected = null, open = open"
        :class="{ 'faq-open': open, 'faq-close': !(open) }"
      >
        <span>+</span>
        <span class="hidden">-</span>
      </button>
    </dt>
    <dd
      class="faq-a overflow-hidden transition-all max-h-0 duration-700"
      style="" x-ref="container1" x-bind:style="selected == 1 ? 'max-height: ' + $refs.container1.scrollHeight + 'px' : ''"
    >
      <div class="inner">
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure rerum in tempore sit ducimus doloribus quod commodi eligendi ipsam porro non fugiat nisi eaque delectus harum aspernatur recusandae incidunt quasi.
      </div>
    </dd>
  </dl>
</div>

以及指向CodePen 的链接。

我想要做的是在单击按钮时将按钮的类从faq-open 切换到faq-close。虽然我实际上可能也需要在父 dt 上切换一个类。

此时,当您单击按钮时,手风琴会展开,但类不会改变。

【问题讨论】:

    标签: tailwind-css alpine.js


    【解决方案1】:

    问题出在这一行

    @click="selected !== 1 ? selected = 1 : selected = null, open = open"
    

    你永远不会改变open的值,它始终是初始化时的值,即open: true

    你需要切换它:

    @click="selected !== 1 ? selected = 1 : selected = null, open = !open"
    

    顺便说一句,您不需要额外的变量selected 来控制隐藏文本,只需一个open 变量就足够了。像这样的:

    <div x-data="{open: true}">
        <dl class="faqs mx-auto max-w-2xl">
          <dt>
            <span class="faq-q">Question</span>
            <button
              type="button"
              class="faq-toggle"
              @click="open = !open"
              :class="open ? 'faq-open' : 'faq-close'"
            >
              <span :class="open ? '' : 'hidden'">+</span>
              <span :class="open ? 'hidden' : ''">-</span>
            </button>
          </dt>
          <dd
            class="faq-a overflow-hidden transition-all max-h-0 duration-700"
            style="" x-ref="container1" x-bind:style="open ? 'max-height: ' + $refs.container1.scrollHeight + 'px' : ''"
          >
            <div class="inner">
              Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure rerum in tempore sit ducimus doloribus quod commodi eligendi ipsam porro non fugiat nisi eaque delectus harum aspernatur recusandae incidunt quasi.
            </div>
          </dd>
        </dl>
    

    【讨论】:

    • 太好了,谢谢! :) ?
    猜你喜欢
    • 2021-12-26
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多