// HTML
<span class="rotatable-text">旋转文字</span>
// CSS
.rotatable-text {
display: inline-block; /* or block, depending on your needs */
transition: transform 0.3s ease-in-out; /* Adjust duration and easing as needed */
}
.rotatable-text:hover {
transform: rotate(360deg);
}
Explanation:
-
HTML: We wrap the text we want to rotate in a
<span>
with the classrotatable-text
. You could use other elements like<div>
,<p>
, etc., depending on your layout needs. -
CSS:
display: inline-block;
: This ensures the element behaves like an inline element but can also have width and height properties, which are necessary for transformations. If you want the element to take up the full width of its container, usedisplay: block;
instead.transition: transform 0.3s ease-in-out;
: This line is crucial. It tells the browser to animate thetransform
property over 0.3 seconds using anease-in-out
transition. You can adjust the duration and the easing function to your liking. Common easing functions includeease
,linear
,ease-in
,ease-out
,ease-in-out
.transform: rotate(360deg);
: This is applied when the mouse hovers over the element. It rotates the element 360 degrees clockwise.
Alternative using JavaScript (for more complex animations or interactions):
const rotatableTexts = document.querySelectorAll('.rotatable-text');
rotatableTexts.forEach(element => {
element.addEventListener('mouseenter', () => {
element.style.transform = 'rotate(360deg)';
});
element.addEventListener('mouseleave', () => {
element.style.transition = 'transform 0.3s ease-in-out'; // Reset transition for smooth return
element.style.transform = 'rotate(0deg)'; // Return to original rotation
});
});
Explanation of the JavaScript version:
querySelectorAll('.rotatable-text')
: This selects all elements with the classrotatable-text
.forEach
: This loops through each selected element.addEventListener('mouseenter', ...)
: This adds an event listener that triggers a function when the mouse enters the element's boundaries. Inside the function, we set thetransform
property torotate(360deg)
.addEventListener('mouseleave', ...)
: This adds an event listener that triggers a function when the mouse leaves the element's boundaries. Inside the function, we reset thetransform
property torotate(0deg)
to return the element to its original position and re-apply the transition for a smooth animation back.
Choose the method that best suits your needs. The CSS-only approach is simpler for basic rotations, while the JavaScript approach offers more flexibility for complex animations and interactions. Remember to include the JavaScript code within <script>
tags in your HTML file, preferably just before the closing </body>
tag.