方法一:js 操作animation

css 中使用动画,会先定义一个@keyframes 在@keyframes里指定 css 样式,动画将在特定事件内逐渐从当前样式更改为新样式。
css 使用动画
第一步:定义动画变化的样式

@keyframes example {
  from {background-color: red;}
  to {background-color: yellow;}
}
@keyframes test {
  0% {background-color: red;}
  100% {background-color: yellow;}
}

第二步:所需元素调用

div {
  width: 100px;
  height: 100px;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
}

js 使用动画

在使用 js 修改 css 样式时,通常是通过

document.getElementById("ele").style.backgroundColor = "#f00"

这种方法无法操作@keyframes。这时候使用document.styleSheets
第一步:通过 document.styleSheets 定义动画变化的样式

document.styleSheets[0].insertRule(
	`@keyframes example {
		0% {background-color: red;}
		100% {background-color: yellow;} }`,
	0
);

第二步:使用 js 修改元素 animation 等属性

document.getElementById("ele").style.animation = "example 1s linear"

即可实现

方法二:js 操作 transition

使用过渡实现动画效果

document.getElementById("ele").style.transition = "width 5s linear";

因为本人原先是需要操作 transform 属性的

document.getElementById("ele").style.transition = "-webkit-transform 1000ms  linear";
document.getElementById("ele").style.webkitTransform = "scale(1) scale(0.65)";

如有错误,欢迎指正,谢谢!
以上内容仅供参考,欢迎大家讨论。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐