如何判断CSS3中设置transition的div是否处于旋转状态?
判断CSS旋转过渡是否处于运行状态的方法
下面是几种实用的方式,帮你判断目标div是否正在执行rotateX的过渡动画:
方法一:监听过渡事件(最可靠)
通过监听transitionstart、transitionend和transitioncancel事件,维护一个状态变量来标记当前是否在旋转:
const targetDiv = document.querySelector('.your-div-selector'); let isRotating = false; // 过渡开始时标记为旋转中 targetDiv.addEventListener('transitionstart', (e) => { // 只针对transform属性的过渡(避免其他属性过渡干扰) if (e.propertyName === 'transform') { isRotating = true; } }); // 过渡正常结束时标记为停止 targetDiv.addEventListener('transitionend', (e) => { if (e.propertyName === 'transform') { isRotating = false; } }); // 过渡被中断(比如中途修改样式)时也标记为停止 targetDiv.addEventListener('transitioncancel', (e) => { if (e.propertyName === 'transform') { isRotating = false; } });
之后直接读取isRotating变量就能知道当前状态,这种方式能精准覆盖过渡的所有生命周期场景。
方法二:对比当前计算样式与目标样式
通过对比元素当前的transform计算值和目标旋转的transform值,判断是否还在过渡中:
const targetDiv = document.querySelector('.your-div-selector'); // 替换成你的目标旋转样式 const targetTransform = 'rotateX(90deg)'; // 计算目标旋转对应的矩阵值 const tempEl = document.createElement('div'); tempEl.style.transform = targetTransform; document.body.appendChild(tempEl); const targetMatrix = getComputedStyle(tempEl).transform; document.body.removeChild(tempEl); function checkRotationState() { const currentMatrix = getComputedStyle(targetDiv).transform; // 注意:由于浮点数精度问题,可考虑用近似匹配(比如对比矩阵数值的差值) return currentMatrix !== targetMatrix; }
这种方法适合单次固定目标的过渡,但如果过渡目标动态变化,需要实时更新targetMatrix。
方法三:使用Web Animations API检测
通过getAnimations()方法获取元素的所有动画实例,筛选出正在运行的transform过渡:
const targetDiv = document.querySelector('.your-div-selector'); function isInRotationTransition() { const animations = targetDiv.getAnimations(); return animations.some(anim => { // CSS过渡对应的动画名称为'none' return anim.animationName === 'none' && anim.playState === 'running' && // 检查是否是transform属性的过渡 anim.effect?.getComputedTiming().propertyIndexList.includes('transform'); }); }
这个方法不需要维护状态变量,每次调用函数即可获取当前状态,兼容性较好。
内容的提问来源于stack exchange,提问作者trip xp
相关产品推荐
相关产品推荐

