求助:实现Hover触发旋转动画停留,离开后平滑归位
解决鼠标离开时元素平滑旋转回初始角度的问题
你的核心问题是混用了CSS transition和animation,且存在几处代码错误,导致鼠标离开时元素直接跳回初始角度。以下是两种解决方案,优先推荐纯CSS的transition方案,更简洁易维护:
方案一:纯CSS Transition实现(推荐)
完全不需要JavaScript,利用CSS的:hover伪类和transition属性就能实现平滑的状态切换:
<div id="modalWrepper1" class="polaroid rotate_left"> <p class="caption">Just a basic explanation of the picture.</p> </div>
.polaroid { width: 280px; height: 200px; padding: 10px 15px 100px 15px; border: 1px solid #BFBFBF; border-radius: 2%; background-color: white; box-shadow: 10px 10px 5px #aaaaaa; } .rotate_left { transform: rotate(-8deg); /* 给transform属性添加过渡,确保状态切换平滑 */ transition: transform 1s 0.25s; /* 兼容旧浏览器前缀可保留,但现代浏览器已无需 */ -ms-transition: -ms-transform 1s 0.25s; -webkit-transition: -webkit-transform 1s 0.25s; } .rotate_left:hover { transform: rotate(0deg); }
说明:
- 把过渡属性
transition统一写在初始状态.rotate_left中,避免重复代码 - 移除了
:hover伪类中重复的样式(只保留变化的transform即可) - 修正了原代码中
:hover里无效的padding: 10px 15px -100px 15px设置
方案二:修正原有的Animation+JS方案
如果你坚持使用CSS动画实现,需要修正以下几处错误:
1. 修复CSS错误
- 修正
@keyframes animatedBack中的拼写错误:form→from - 给动画类添加
animation-fill-mode: forwards,确保动画结束后停留在目标状态 - 移除冲突的
transition属性
2. 修复JavaScript错误
- 循环条件改为
i < elements.length(原i <= elements.length会导致数组越界) - 添加
mouseout事件监听,触发返回动画
修正后的完整代码:
<div id="modalWrepper1" class="polaroid rotate_left"> <p class="caption">Just a basic explanation of the picture.</p> </div>
.polaroid { width: 280px; height: 200px; padding: 10px 15px 100px 15px; border: 1px solid #BFBFBF; border-radius: 2%; background-color: white; box-shadow: 10px 10px 5px #aaaaaa; } .rotate_left { transform: rotate(-8deg); -ms-transform: rotate(-8deg); -webkit-transform: rotate(-8deg); } @keyframes animationBegining { from { transform: rotate(-8deg); -ms-transform: rotate(-8deg); -webkit-transform: rotate(-8deg); } to { transform: rotate(0deg); -ms-transform: rotate(0deg); -webkit-transform: rotate(0deg); } } @keyframes animatedBack { from { /* 修正拼写错误 form → from */ transform: rotate(0deg); -ms-transform: rotate(0deg); -webkit-transform: rotate(0deg); } to { transform: rotate(-8deg); -ms-transform: rotate(-8deg); -webkit-transform: rotate(-8deg); } } .animated { animation: animationBegining 2s forwards; /* 添加forwards保持动画结束状态 */ } .animatedback { animation: animatedBack 2s forwards; /* 添加forwards保持动画结束状态 */ }
const elements = document.getElementsByClassName('rotate_left'); for (let i = 0; i < elements.length; i++) { // 修正循环条件 const el = elements[i]; el.addEventListener('mouseover', function() { el.classList.add('animated'); el.classList.remove('animatedback'); }); el.addEventListener('mouseout', function() { // 添加mouseout事件 el.classList.add('animatedback'); el.classList.remove('animated'); }); }
内容的提问来源于stack exchange,提问作者Krissz
相关产品推荐
相关产品推荐

