如何获得div动画的当前状态?

时间:2022-11-28 09:03:34

I am using Safari, thus to make it easier to answer my question I will just use the -webkit- prefix on my animations.

我正在使用Safari,因此为了更容易回答我的问题,我将在我的动画上使用-webkit-前缀。

I am making a menu that is in the corner. When the user hovers, it spans the entire website until the user leaves the menu, then it recedes again.

我正在制作一个位于角落的菜单。当用户盘旋时,它会跨越整个网站,直到用户离开菜单,然后再次退出。

The only problem I have is that if the user doesn't wait until the menu bar is completely spanning the webpage, then the bar flickers to get to its position in the animation. What can I do to fix this and make the animation start from the current width of the div? Here is my CSS:

我唯一的问题是,如果用户不等到菜单栏完全跨越网页,则条形闪烁以到达其在动画中的位置。我该怎么做才能解决这个问题并让动画从div的当前宽度开始?这是我的CSS:

#menubar {
    /* Menu bar styling */
}

#menubar:hover {
    -webkit-animation: openMenu 2s;
    width: 100%;
}

#menubar:not(:hover) {
    -webkit-animation: closeMenu 2s;
    width: 75px;
}

/* Animations */

@-webkit-keyframes openMenu {
    from {width:75px;}
    to {width:100%;}
}

@-webkit-keyframes closeMenu {
    from {width:100%;} /* How do I get the current width of the div here instead of using width:100%;? */
    to {width:75px;}
}

Thanks in advance for your help, everyone.

感谢您的帮助,大家。

1 个解决方案

#1


Do you need keyframes? You could achieve the same result using transitions, like in this fiddle.

你需要关键帧吗?你可以使用过渡来获得相同的结果,比如这个小提琴。

#menubar {
    /* Menu bar styling */
    width: 75px;

    transition: width 2s;
}

#menubar:hover {
    width: 100%;
}

Basically, you tell that the menubar should be at 100% when hovered, at 75px when idle, and the width transition should last 2s and everything works.

基本上,你告诉你,当徘徊时,菜单栏应该是100%,闲置时是75px,宽度转换应该持续2s,一切正常。

#1


Do you need keyframes? You could achieve the same result using transitions, like in this fiddle.

你需要关键帧吗?你可以使用过渡来获得相同的结果,比如这个小提琴。

#menubar {
    /* Menu bar styling */
    width: 75px;

    transition: width 2s;
}

#menubar:hover {
    width: 100%;
}

Basically, you tell that the menubar should be at 100% when hovered, at 75px when idle, and the width transition should last 2s and everything works.

基本上,你告诉你,当徘徊时,菜单栏应该是100%,闲置时是75px,宽度转换应该持续2s,一切正常。