如何检测移动端浏览器对CSS @keyframes动画的支持并处理不兼容问题
实现方案
方案一:不兼容浏览器自动重定向
你之前用的检测方案大概率未覆盖老旧移动端仅支持的-webkit-前缀规则,导致误判,使用以下检测逻辑即可实现精准识别跳转,将这段JS放在页面<head>标签最靠前的位置优先执行,避免无效资源加载:
function checkCSSAnimationSupport() { const elStyle = document.createElement('div').style; // 同时兼容标准属性和webkit前缀属性,适配老版本安卓、iOS浏览器 return 'animation' in elStyle || 'WebkitAnimation' in elStyle; } if (!checkCSSAnimationSupport()) { // 替换为你的无动画版本站点地址 window.location.replace('/no-animation-site.html'); }
方案二:无跳转兼容降级(体验更优,可选)
如果不想拆分站点,可以直接修改现有代码做兼容,不支持动画的浏览器直接展示静态文本,无需跳转:
1. 修改CSS代码
补充前缀规则,同时给字符元素设置默认可见属性,避免不支持动画的浏览器文本隐藏:
.char{ font-size: 40px; height: 40px; /* 默认可见,支持动画的环境会被动画初始状态覆盖 */ opacity: 1; transform: none; animation: an 1s ease-out 1 both; /* 兼容webkit前缀 */ -webkit-animation: an 1s ease-out 1 both; display: inline-block; } /* 前缀版本keyframes */ @-webkit-keyframes an{ from{ opacity: 0; -webkit-transform: perspective(500px) translate3d(-35px, -40px, -150px) rotate3d(1, -1, 0, 35deg); } to{ opacity: 1; -webkit-transform: perspective(500px) translate3d(0, 0, 0); } } @keyframes an{ from{ opacity: 0; transform: perspective(500px) translate3d(-35px, -40px, -150px) rotate3d(1, -1, 0, 35deg); } to{ opacity: 1; transform: perspective(500px) translate3d(0, 0, 0); } }
2. 修改JS代码
仅在动画支持的环境下执行字符拆分和动画初始化,不支持的环境保留原始文本:
function checkCSSAnimationSupport() { const elStyle = document.createElement('div').style; return 'animation' in elStyle || 'WebkitAnimation' in elStyle; } function myFunc(text) { let newDom = ''; const animationDelay = 6; for(let i = 0; i < text.innerText.length; i++) { newDom += '<span class="char">' + (text.innerText[i] === ' ' ? ' ' : text.innerText[i]) + '</span>'; } text.innerHTML = newDom; const length = text.children.length; for(let i = 0; i < length; i++) { text.children[i].style.animationDelay = animationDelay * i + 'ms'; text.children[i].style.webkitAnimationDelay = animationDelay * i + 'ms'; } } if (checkCSSAnimationSupport()) { const text = document.querySelectorAll('.th'); myFunc(text[0]); myFunc(text[1]); }
额外提示
你提供的DOM结构中h2标签的闭合标签误写为</div>,建议修正为</h2>避免浏览器解析异常。
内容的提问来源于stack exchange,提问作者SimpleGuy_
相关产品推荐
相关产品推荐

