I have a container div set with overflow:hidden that swaps between two cards, with only one visible at a time:

[card 1 | card 2]

I have jquery set up so that, when a user clicks on a button, it toggles a class, .slid, on the div, with stylus styling that changes its margin-left parameter to -400 or so.

     .container
            &.slid {
                margin-left: -400px;

This all works; whenever you press the button, the cards flip back and forth.

I wanted to write an animation so that the cards will slide back and forth instead, so I changed my stylus code to

       .container{
            animation: slideout 1s;
            &.slid {
                margin-left: -400px;
                animation: slidein 1s;
            }

with corresponding animations:

@keyframes slidein {
    from {
        margin-left: 0px;
    }

    to {
        margin-left: -400px
    }

}

@keyframes slideout {
    from {
        margin-left: -400px;
    }

    to {
        margin-left: 0px;
    }

}

This also works more or less as intended, but I have one problem: since the stylus code is set to run the animation on load, a page refresh will run the slideout animation on page load. Is there a way around this easily that still preserves the animations sliding back and forth?

有帮助吗?

解决方案

In my opinion I think that instead of applying the slideout animation to the container and toggling the application of a single .slid class which defines the slidein animation, you should do as following:

1- Do not apply the animation directly to the container class.

2- Define two classes .slid-in (your current .slid) and .slid-out that define the slidein and slideout animations respectively. Something like:

.container{
        &.slid-in {
            margin-left: -400px;
            animation: slidein 1s;
        }
        &.slid-out {
            margin-left: 0px;
            animation: slideout 1s;
        }
}

3- Update your code in order to apply the .slid-in class the first time the button is pressed, and toggling between .slid-in and .slid-out afterwards.

By doing it this way, you would prevent the slideout animation to be applied on page load, since the .container class is applied right away as deduced from your explanation.

其他提示

You can influence the loading order of the CSS by just placing it at the bottom of the page. That will make sure the html is loaded before the CSS is applied. Ofcourse if you are bringing things in with javascript or AJAX this won't be a bulletproof solution. It should be ok if all the elements are in the html itself.

I hope that helps!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top