每5秒/间隔运行动画

Dev*_*Joe 5 javascript css jquery

我想每5秒钟摇晃一次此文本,因此我尝试在CSS中实现动画并通过jQuery设置间隔,但是似乎出了点问题……想法丢失了什么?这是一个小提琴: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>
Run Code Online (Sandbox Code Playgroud)

Con*_*roß 5

您可以使用纯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);
    }
}
Run Code Online (Sandbox Code Playgroud)
<div class="shk">Shake me</div>
Run Code Online (Sandbox Code Playgroud)