You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测浏览器对@keyframes translate3d动画的兼容性

检测@keyframes+translate3d动画兼容性解决方案

前置说明

你之前用@supports检测无效是正常现象:多数旧版安卓内置浏览器(安卓4.0-4.4阶段的系统WebView)对@supports规则的支持不完善,无法正确识别@keyframes和translate3d组合的兼容情况,因此更推荐用JavaScript做特征检测。

核心检测代码

function check3dAnimationSupport() {
  // 检测CSS动画支持
  let animationSupported = false,
    animationstring = 'animation',
    keyframeprefix = '',
    domPrefixes = 'Webkit Moz O ms Khtml'.split(' '),
    pfx  = '',
    elm = document.createElement('div');
  if( elm.style.animationName !== undefined ) { animationSupported = true; }
  if( animationSupported === false ) {
    for( let i = 0; i < domPrefixes.length; i++ ) {
      if( elm.style[ domPrefixes[i] + 'AnimationName' ] !== undefined ) {
        pfx = domPrefixes[ i ];
        animationstring = pfx + 'Animation';
        keyframeprefix = '-' + pfx.toLowerCase() + '-';
        animationSupported = true;
        break;
      }
    }
  }
  if(!animationSupported) return false;
  // 检测translate3d支持
  const transforms = {
    'webkitTransform':'-webkit-transform',
    'OTransform':'-o-transform',
    'msTransform':'-ms-transform',
    'MozTransform':'-moz-transform',
    'transform':'transform'
  };
  let has3d = false;
  for(let t in transforms) {
    if( elm.style[t] !== undefined ) {
      elm.style[t] = 'translate3d(1px,1px,1px)';
      has3d = window.getComputedStyle(elm).getPropertyValue(transforms[t]);
    }
  }
  return (has3d !== undefined && has3d.length > 0 && has3d !== "none");
}

调用check3dAnimationSupport()会返回布尔值,true代表兼容,false代表不兼容。

实现方案1:不兼容时直接禁用动画

修改后的CSS代码

h1,h2{
  height: 40px;
  opacity: 1; /* 默认设置不透明,避免动画加载失败文本消失 */
  animation: an 1s ease-out 1 both;
}
/* 不兼容时直接取消动画 */
body.no-3d-animation h1,
body.no-3d-animation h2 {
  animation: none;
}
@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);
  }
}

JS触发逻辑

window.addEventListener('DOMContentLoaded', function() {
  if(!check3dAnimationSupport()) {
    document.body.classList.add('no-3d-animation');
  }
})

实现方案2:不兼容时重定向到无动画版本

替换上面的JS触发逻辑即可:

window.addEventListener('DOMContentLoaded', function() {
  if(!check3dAnimationSupport()) {
    // 替换为你的无动画版本页面地址
    window.location.href = './no-animation-version.html';
  }
})

额外提醒

你提供的HTML代码存在语法错误,<h2>的闭合标签错写为</div>,请修正为</h2>:

<h1 id="h1" class="th">Test Texts</h1>
<h2 id="h2" class="th">Also Test Texts..</h2>

内容的提问来源于stack exchange,提问作者SimpleGuy_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 22:30:03