针对Safari不支持SVG负值的解决方案求助
解决Safari中SVG路径动画不生效的问题
你的问题核心在于Safari对CSS动画中动态修改<path>的d属性支持有限,另外代码里还有个小错误:opacity: 100是无效的,opacity的取值范围是0到1,应该写成opacity: 1。
我们可以换个思路,不用修改路径本身,而是通过transform属性实现元素的移动和翻转——这是Safari完全支持的方案,同时保留原来的描边动画效果:
修改要点:
- 移除动画中修改
d属性的代码,改用transform: translateX()控制位置,transform: scaleX(-1)实现翻转效果 - 修正opacity的取值错误
- 调整动画关键帧的时间点,和原效果对齐
修改后的完整代码:
<?xml version="1.1" encoding="UTF-8"?> <svg id="logo-layers" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 41 21"> <defs> <style> .cls-1 { stroke: #4e2164; stroke-linecap: round; stroke-dasharray: 63; animation-name: o-ani; animation-duration: 3s; animation-timing-function: linear; animation-fill-mode: forwards; transform-origin: center; } .cls-1, .cls-2 { fill: none; stroke-miterlimit: 10; } .cls-2 { stroke: #CCCC00; stroke-linecap: round; stroke-dasharray: 47; animation-name: j-ani; animation-duration: 3s; animation-timing-function: linear; animation-fill-mode: forwards; transform-origin: center; opacity: 0; } @keyframes o-ani { 0%{ stroke-dashoffset: 63; transform: translateX(0) scaleX(1); } 20%{ stroke-dashoffset: 0; } 21%{ transform: translateX(0) scaleX(1); } 41%{ transform: translateX(20px) scaleX(-1); } 100%{ transform: translateX(20px) scaleX(-1); stroke-dashoffset: 0; } } @keyframes j-ani { 0%{ opacity: 0; stroke-dashoffset: 47; transform: translateX(0) scaleX(-1); } 40%{ opacity: 0; } 41%{ opacity: 1; } 42%{ stroke-dashoffset: 47; } 62%{ stroke-dashoffset: 0; } 63%{ transform: translateX(0) scaleX(-1); } 83%{ transform: translateX(-20px) scaleX(1); } 100%{ transform: translateX(-20px) scaleX(1); stroke-dashoffset: 0; opacity: 1; } } </style> </defs> <path id="o-letter" class="cls-1" d="M10.5,.5c5.523,0,10,4.477,10,10s-4.477,10-10,10S.5,16.023,.5,10.5,4.977,.5,10.5,.5Z"/> <path id="j-letter" class="cls-2" d="M30.5,.5c-5.523,0-10,4.477-10,10s4.477,10,10,10,10-4.477,10-10"/> </svg>
关键改动说明:
- 给两个路径添加
transform-origin: center,确保翻转和移动以元素中心为基准 o-letter的动画:通过translateX(20px)移动到右侧,scaleX(-1)实现水平翻转,模拟原路径切换的效果j-letter的动画:通过translateX(-20px)移动到左侧,scaleX(1)恢复正向,同时修正opacity为1- 保留了原有的描边绘制动画(stroke-dashoffset),确保和原效果一致
这个方案在Chrome、Firefox和Safari中都能正常运行,不需要修改路径的绝对坐标,而是通过更兼容的transform属性实现需求。
内容的提问来源于stack exchange,提问作者Jackie0
相关产品推荐
相关产品推荐

