首页 > 解决方案 > How can I create toggle action that only toggles once?

问题描述

I have button with a masked number phone :

I would like to reveal the number phone but that the toogle work only once (no return)

My stimulus-controller :

import {Controller} from 'stimulus'

export default class extends Controller {
  static targets = ['item', 'item2']
  static classes = ['hidden']

  connect() {
    this.class = this.hasHiddenClass ? this.hiddenClass : 'hidden'
    console.log(this.hiddenClass)
  }

  toggle() {
    this.itemTargets.forEach(item => {
      item.classList.toggle(this.class)
    })
  }

  show() {
    this.itemTargets.forEach(item => {
      item.classList.remove(this.class)
    })

  }

  hide() {
    this.item2Targets.forEach(item2 => {
      item2.classList.add(this.class)
    })
  }
}

I'm trying two methods :

With a toggle function :

  <div data-controller="reveal" data-reveal-hidden-class="hidden">
    <button data-action="reveal#toggle" type="button">
      <p data-reveal-target="item" class="hidden mt-4">telephone </p>
      <p data-reveal-target="item" class="mt-4"><a href="tel:+33500000000">500000000</a></p>
    </button>
  </div>

With show and hide functions :

<div data-controller="reveal" data-reveal-hidden-class="hidden">
  <button data-action="reveal#show reveal#hide" type="button">
    <p data-reveal-target="item" class="hidden mt-4">telephone </p>
    <p data-reveal-target="item2" class="mt-4"><a href="tel:+33500000000">500000000</a></p>
  </button>
</div>

The two methods works fine but I would like that the user can switch only once

标签: javascriptstimulusjs

解决方案


推荐阅读