css 媒体查询后动画未触发

css animation not triggering after media query

我有一个看起来像这样的列表

<ul class="timeline-container">
   <li class="timeline-item-container">
       <div class="timeline-item></div>
   </li>
   <li class="timeline-item-container">
       <div class="timeline-item></div>
   </li>
</ul>

我声明了 2 个动画

    @keyframes slideLeft
    {
        from {
            transform: translateX(1000px);
        }

        to {
            transform: translateX(0);
        }
    }

    @keyframes slideRight
    {
        from {
            transform: translateX(-1000px);
        }

        to {
            transform: translateX(0);
        }
    }

然后在我的 css 我有这个:

.timeline-item
{
    animation: slideRight .6s ease both;

    @media (max-width:767px)
    {
        animation: slideLeft .6s ease both;
    }
}

所以这很完美,当屏幕小于 767 像素时,我列表中的所有项目都从右侧滑入,当屏幕大于 767 像素时,则从左侧滑入。当我调整屏幕大小时,动画再次播放。

现在我希望当屏幕大于 767px 时,列表中的每个奇数项都从右侧滑入,所以我添加:

.timeline-item-container:nth-child(even) .timeline-item
{
   @media (min-width:767px)
   {
        animation: slideLeft .6s ease both;
   }
}

如果我刷新页面,这会起作用,但如果我调整屏幕大小,动画就不会播放。它应该像以前一样在屏幕调整大小时播放动画

我知道动画在那里,因为如果我刷新它,它就会播放,只是在我调整屏幕大小后不会播放

任何帮助都适用

https://jsfiddle.net/7pk6yncd/

您不能将 @media 放在 css 规则中。

反之亦然,给你:

    .timeline-item
    {
        animation: slideRight .6s ease both;

    }

    @keyframes slideLeft
    {
        from {
            transform: translateX(1000px);
        }

        to {
            transform: translateX(0);
        }
    }

    @keyframes slideRight
    {
        from {
            transform: translateX(-1000px);
        }

        to {
            transform: translateX(0);
        }
    }

    @media (max-width:767px)
    {
        .timeline-item{
            animation: slideLeft .6s ease both;
        }
        .timeline-item-container:nth-child(even) .timeline-item
        {
                animation: slideRight .6s ease both;
        }
    }

我认为唯一的办法就是用不同的名字定义同一个动画两次。实际上你使用的动画是一样的,所以媒体查​​询不会再次触发它。

.box {
  background:red;

  animation:fromLeft 2s linear forwards;
}

@media all and (max-width:600px) {
.box {
  background:blue;
  display:block;
  animation:fromLeft-alt 2s linear forwards;

}

}

@keyframes fromLeft {
   from {
     transform:translateX(-100%);
   }
}
@keyframes fromLeft-alt {
   from {
     transform:translateX(-100%);
   }
}
<div class="box">
  some content
</div>