[英]CSS transform transition on SVG element
我正在尝试使用 CSS 过渡显示并立即为 SVG 元素的旋转设置动画。
const node = getSVGElement(); // Has 'transform' set to 'rotate(0)'
node.classList.add('svg-animation');
const parent = document.getElementById('someDiv');
parent.appendChild(node);
setTimeout(() => {
node.setAttribute('transform', `rotate(${someOtherValue})`);
}
}, 50);
在 CSS 中:
.svg-animation {
transition: transform 0.5s ease-in-out;
}
这在 Chrome 中按预期工作,但 Firefox 和 Safari 显示该元素时根本不对其进行动画处理。 是否应该使用不同的语法(或方法)以便它在这些浏览器中工作(我不关心 IE)?
在这里,您有两种不同的方法来解决问题。 首先使用 JavaScript,然后使用 SMIL。 从您的代码示例中不清楚问题是什么,但请确保在找到元素之前加载 DOM,然后在元素上使用样式属性而不是设置属性。
采取什么解决方案取决于您。 我会说这取决于上下文。
var someOtherValue = 90; document.addEventListener('DOMContentLoaded', e => { const node = document.querySelector('rect'); node.classList.add('svg-animation'); setTimeout(() => { node.style.transform = `rotate(${someOtherValue}deg)`; }, 500); });
.svg-animation { transition: 1s ease-in-out; }
<svg viewBox="0 0 100 100" width="200"> <g transform="translate(50 50)"> <rect x="-20" y="-20" width="40" height="40" fill="navy"/> </g> </svg>
<svg viewBox="0 0 100 100" width="200"> <g transform="translate(50 50)"> <rect x="-20" y="-20" width="40" height="40" fill="navy"> <animateTransform attributeName="transform" attributeType="XML" type="rotate" from="0" to="90" calcMode="spline" keyTimes="0;1" keySplines=".5 0 .5 1" begin="1s" dur="1s" fill="freeze"/> </rect> </g> </svg>
而不是setAttribute
尝试 css 转换; 记得指定单位。
node.style.transitionDuration = '1s';
let rotation_angle_deg = 10
node.style.transform = 'rotate('+rotation_angle_deg+'deg)';
我只在 Safari 15.5 中对此进行了测试,但它在那里工作,我可以确认 setAttribute 忽略任何transition-duration
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.