简体   繁体   English

单击时是否可以在 next.js 图像上添加旋转 animation?

[英]Is it possible to add a rotate animation on an next.js image when clicked?

I want to add an animation to an next.js image.我想将 animation 添加到 next.js 图像。 It should rotate by 360 degree when clicked one time.单击一次它应该旋转 360 度。 I am not able to get the desired result by trying toggle class. I hope someone can help me.我无法通过尝试切换 class 获得所需的结果。我希望有人能帮助我。 Thanks in advance!提前致谢!

I already tried this, but I can't get it to work:我已经尝试过这个,但我无法让它工作:

<Image
src="/images/user_rotate.png"
height={20}
width={20}
alt="user_rotate"    
onClick={rotate_user}       
id="rotate_user"         
/>

function rotate_user(){
    var rotation_symbol = document.getElementById("rotate_user");
    rotation_symbol.classList.toggle("rotated");
}

My CSS-Module:我的 CSS 模块:

.rotated {
    animation: rotation 2s;
}

@keyframes rotation {
    0% {
        transform: rotate(32deg)
    }

    10% {
        transform: rotate(64deg)
    }

    20% {
        transform: rotate(96deg)
    }

    30% {
        transform: rotate(128deg)
    }

    40% {
        transform: rotate(160deg)
    }

    50% {
        transform: rotate(192deg)
    }

    60% {
        transform: rotate(224deg)
    }

    70% {
        transform: rotate(256deg)
    }

    80% {
        transform: rotate(288deg)
    }

    90% {
        transform: rotate(310deg)
    }

    100% {
        transform: rotate(360deg);
    }
}
import { useSpring, animated } from 'react-spring'

const Image = () => {
  const [animation, setAnimation] = useSpring(() => ({
    transform: 'rotate(0deg)'
  }))

  const handleClick = () => {
    setAnimation({
      transform: 'rotate(360deg)'
    })
  }

  return (
    <animated.img
      style={animation}
      onClick={handleClick}
      src='/image.jpg'
      alt='Animated image'
    />
  )
}

This will create an animation that rotates the image 360 degrees when it is clicked.这将创建一个 animation,它在单击时将图像旋转 360 度。 The useSpring hook returns an object with an animation property that can be used to apply the animation to the image using the style prop. useSpring 钩子返回一个 object 和一个 animation 属性,该属性可用于使用 style 属性将 animation 应用于图像。

Using event.target will give you the object that was clicked.使用event.target将为您提供被点击的 object。 Combining that with the CSS transition modifier will rotate elements smoothly.将其与 CSS 过渡修饰符结合使用将平滑地旋转元素。

<body>
    <main>
        <button id="button" style="transition: all 0.5s; background-color: green; width: 100px; height: 50px; border: none; border-radius: 5px; color: lightblue; font-size: 18px" onclick="spin()">click me</button>
    </main>

    <script type = "text/javascript">
        var rotation = 0
        function spin() {
            rotation += 45;
            event.target.style.transform = "rotate(" + rotation + "deg)";
        }
    </script>
</body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM