javascript - 每 5 秒/间隔运行一次动画

标签 javascript jquery css

我想每 5 秒摇动一下这个文本,所以我尝试在 CSS 中实现一个动画并通过 jQuery 设置一个间隔,但似乎有些不对劲……想法缺少了什么?这是一个 fiddle :https://jsfiddle.net/s909gu2s/1/

.shk {
    transform: translate3d(0, 0, 0);
    backface-visibility: hidden;
    -webkit-animation-name: shake;
    -webkit-animation-duration: 1s;
    -webkit-animation-iteration-count: infinite;
    -webkit-animation-timing-function: linear;
    -webkit-animation-delay: 0s;
}

@keyframes shakeMe {
    10%, 90% {
        transform: translate3d(-5px, 0, 0);
    }

    20%, 80% {
        transform: translate3d(5px, 0, 0);
    }

    30%, 50%, 70% {
        transform: translate3d(-5px, 0, 0);
    }

    40%, 60% {
        transform: translate3d(5px, 0, 0);
    }
}

$(document).ready(function() {
    setInterval(function() {
        $(".shk").css("animation", "shakeMe");
    }, 500);
});

<div class="shk">Shake me</div>

最佳答案

您可以使用纯 CSS 来完成,不需要 JS/jQuery。为了实现这一点,我将 animation-duration 设置为 5 秒,然后将所有百分比值乘以 0.2(因为 5 秒中的 1 秒 => 20%)。然后在最高百分比值之后转换回 0px。瞧,每 5 秒摇晃一次:

.shk {
    transform: translate3d(0, 0, 0);
    backface-visibility: hidden;
    animation-name: shakeMe;
    animation-duration: 5s;
    animation-iteration-count: infinite;
    animation-timing-function: linear;
}

@keyframes shakeMe {
    2%, 18% {
        transform: translate3d(-5px, 0, 0);
    }

    4%, 16% {
        transform: translate3d(5px, 0, 0);
    }

    6%, 10%, 14% {
        transform: translate3d(-5px, 0, 0);
    }

    8%, 12% {
        transform: translate3d(5px, 0, 0);
    }
    
    18.1% {
        transform: translate3d(0px, 0, 0);
    }
}
<div class="shk">Shake me</div>

关于javascript - 每 5 秒/间隔运行一次动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47136168/

相关文章:

javascript - 一定数量的 px 后边距底部不动

javascript - HTML + Node.js 文件上传

javascript - 鼠标悬停时不显示选择列表标题

jquery - Jquery 中的 DatePicker 大小

css - 2 Bootstrap 网站不是背景图片没有响应

javascript - 自定义 Jgraph mxCell 的连接输入和输出

javascript - 将 "strict mode"写入一处,使其对所有 `.js` 文件代码生效

javascript - jQuery 自动完成(devbridge)lookupFilter 搜索多个属性

css - 使用未定义的 CSS 媒体查询

javascript - 在javascript中可以使用css3线夹吗?