三种方式实现简单动画

setInterval实现平移动画

/** setInterval */
const setIntervalDom = document.getElementsByClassName("setInterval")[0];

let marginLeftNumber2 = 0;

let timer = setInterval(() => {
     
  marginLeftNumber2 += 2;
  setIntervalDom.style.marginLeft = marginLeftNumber2 + "px";
  if (marginLeftNumber2 >= 1201) {
     
    clearInterval(timer);
  }
}, 14);

RequestAnimationFrameDom实现平移动画

const RequestAnimationFrameDom = document.getElementsByClassName(
  "requestAnimationFrame"
)[0];
/** requestAnimationFrame */

let marginLeftNumber = 0;

function RequestAnimationFrameFun() {
     
  marginLeftNumber++;
  RequestAnimationFrameDom.style.marginLeft = marginLeftNumber + "px";
  if (marginLeftNumber <= 1200) {
     
    requestAnimationFrame(RequestAnimationFrameFun);
  }
}

requestAnimationFrame(RequestAnimationFrameFun);

css3实现动画

<style>
@keyframes move {
      
        from {
      
          margin-left: 0;
        }
        to {
      
          margin-left: 1201px;
        }
      }

.css3 {
      
  animation: move 8333ms linear forwards;
}
style>
  <body>
	<div class="moveBox css3">css3动画div>
  body>

三种实现动画方式的区别

setInterval

众所周知,setinterval的计时是不准确的,setinterval的所实现的动画,是三种方式中最不流畅的,换句话说,略显卡顿。

RequestAnimationFrame

根据浏览器的帧数渲染动画,每一帧就会调用一次RequestAnimationFrame,浏览器一般是60hz,当然还依赖设备的具体刷新率
三种方式实现简单动画_第1张图片
刷新率越高的设备,动画会更流畅。

css3

我们常说,能用css实现的效果,就尽量不使用js来实现,css3动画属性animation也能满足前端基础动画的需求。
但是,css3的动画,当用户切出视窗时,动画不会默认暂停。

解决css3动画,切出视窗时,不会默认暂停。

    <style>
      .moveBox {
     
        width: 100px;
        height: 100px;
        background-color: black;
        color: white;
        text-align: center;
        margin-top: 20px;
        word-wrap: break-word;
        word-break: break-all;
      }

      @keyframes move {
     
        from {
     
          margin-left: 0;
        }
        to {
     
          margin-left: 1201px;
        }
      }

      .css3 {
     
        animation: move 8333ms linear forwards;
      }
      .css3Stop {
     
        animation-play-state: paused !important;
      }
    </style>
  
  <body>
    <div class="moveBox css3">css3动画</div>
  </body>

js代码监听页面的视窗是否展现visibilitychange。

const css3Dom = document.getElementsByClassName("css3")[0];
document.addEventListener(
  "visibilitychange",
  function () {
     
    console.log(document.visibilityState); // hidden or visible
    if (document.visibilityState === "hidden") {
     
      css3Dom.setAttribute("class", "moveBox css3 css3Stop");
    } else {
     
      css3Dom.setAttribute("class", "moveBox css3");
    }
  },
  false
);

你可能感兴趣的:(前端逻辑基础,css,前端动画,raf,css3,setinterval)