CSS - 在关键帧中触发悬停

CSS - Trigger hover in keyframes

本文关键字:悬停 关键帧 CSS      更新时间:2023-09-26

我想让图像像心脏一样悸动。图像悸动3秒后,图像自动翻转1秒,然后图像再次悸动,动作无限。我可以使图像悸动,但仍然无法在 1 秒后自动翻转。

这是我的网页代码

<div class=center>
    <div class="flip">
        <div class="flip-child">
            <div class="front">
                <img src="<?php ABSPATH; ?>/wordpress/logo/logo.png" alt="front" />
            </div>
            <div class="back">
                <a href="<?php ABSPATH; ?>/wordpress/menu.html"> <img src="<?php ABSPATH; ?>/wordpress/logo/back.png" alt="back" /> </a>
            </div>
        </div>
    </div>
</div>

这是 css 脚本

body { 
    background: #fff;   
} 
.center {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
.flip {
  perspective:1000px;
}
.flip:hover .flip-child,
.flip.hover .flip-child {
  transform:rotateY(180deg);
}
.flip,.front,.back{
  width: 284px;
  height: 284px;
}
.flip-child {
  transition:.8s; /* flip */
  transform-style:preserve-3d;
  position:relative;
}
.front,
.back {
  backface-visibility:hidden;
  position:absolute;
  top:0;
  left:0;
}
.front {
  z-index:2;
  transform:rotateY(0deg);
}
.front img{
  animation: blink 1s infinite;
}
.back {
  transform:rotateY(180deg);
}
/* For Chrome, Safari, Opera  */
@-webkit-keyframes blink {
    0%   {width: 284px; height: 284px; margin: -0.5px 0 0 -0.5px;}
    20%  {width: 280px; height: 280px; margin: 0 0 0 0;}
    40%  {width: 276px; height: 276px; margin: 0.5px 0 0 0.5px;}
    60%  {width: 272px; height: 272px; margin: 1px 0 0 1px;}
    80%  {width: 276px; height: 276px; margin: 0.5px 0 0 0.5px;}
    100% {width: 280px; height: 280px; margin: 0 0 0 0;}
}
/* Standard Syntax */
@keyframes blink {
    0%   {width: 284px; height: 284px; margin: -0.5px 0 0 -0.5px;}
    20%  {width: 280px; height: 280px; margin: 0 0 0 0;}
    40%  {width: 276px; height: 276px; margin: 0.5px 0 0 0.5px;}
    60%  {width: 272px; height: 272px; margin: 1px 0 0 1px;}
    80%  {width: 276px; height: 276px; margin: 0.5px 0 0 0.5px;}
    100% {width: 280px; height: 280px; margin: 0 0 0 0;}
}

添加以下JavaScript代码

var flip = document.querySelector('.flip');
var state = 0;
setInterval(function() {
    state = (state + 1) % 4;
  if(state == 0)
        flip.classList.remove('hover')
  else if(state == 3)
        flip.classList.add('hover')
}, 1000)

如果你使用 jquery,请将其包装在

$(function() {
    ... code goes here
});

如果不使用 jquery (kudos),那么要么确保 javscript 位于".flip"元素下方,要么将其包装在

document.addEventListener('DOMContentLoaded', function() {
    ... code goes here
});

工作小提琴