简体   繁体   中英

AMP: Toggle CSS Class

I am generating an amp template and I have a button that toggles the visibility of an amp-sidebar . The code is as follows:

<button class="button .closed icon" on='tap:sidebar1.toggle'></button>

The side-bar toggles as expected. However, I also want to the icon displayed to be changed depending on the state (open or closed).

I have the two classes for doing so:

  • button .closed (hamburger menu icon)

  • button .open (cross)

The shared class "icon" should remain the same between the two. I also want to keep the 'tap:sidebar1.toggle' so the menu will still toggle.

One way of achieving this would be by using an amp-state to keep track of whether the sidebar is open or closed. Then you can bind the button's class using this state to style it accordingly.

Initialise an amp-state like follows :

<amp-state id = "sbOpen">
    <script type = "application/json">
        false
    </script>
</amp-state>

and now change your sidebar code as follows :

<amp-sidebar

 on="sidebarOpen:AMP.setState({sbOpen});sidebarClose:AMP.setState({sbOpen})" 

and finally your button tag should be something like this :

<button class="button closed icon" on='tap:sidebar1.toggle'
        [class]=" 'button icon ' + (sbOpen?'open':'closed) "></button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM