>  기사  >  웹 프론트엔드  >  JS 캐러셀 차트에 여유 기능 캡슐화

JS 캐러셀 차트에 여유 기능 캡슐화

高洛峰
高洛峰원래의
2017-01-16 14:37:081130검색

캐러셀의 뿌리는 실제로 이징 함수의 캡슐화입니다. 캐러셀이 달리는 자동차라면 이징 함수는 그 엔진입니다. 오늘 이 글에서는 여러분만의 이징 함수를 캡슐화해 보겠습니다. ~

요구의 관점에서 시작하여 먼저 간단한 요구를 합니다.

1. 페이지의 상자가 시작 위치에서 일정한 속도로 이동하도록 하는 방법입니다. 200px로 올바르게 이동합니까?

분석:

1) offsetLeft 속성을 통해 얻을 수 있는 상자가 어디에 있는지 알아야 합니다.

2) 상자가 일정한 속도로 움직이도록 하려면; speed, js는 꼭 필요합니다. setInterval;

3) 상자를 오른쪽으로 실행하시겠습니까? 즉, 왼쪽 여백과 왼쪽 위치를 포함하여 상자와 왼쪽 시작점 사이의 거리를 지속적으로 변경해야 합니다. 여기서는 왼쪽 절대 위치를 변경하기로 선택했습니다. 시작점에서 200px 이상 중지하고 싶으면 ClearInterval을 사용하면 됩니다.

그런 다음 코드로 직접 이동

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8" />
  <title>Document</title>
  <style type="text/css">
   * {
    margin: 0;
    padding: 0;
   }
   div {
    position: absolute;
    top: 50px;
    width: 100px;
    height: 100px;
    background-color: red;
   }
   input {
    width: 100px;
    height: 30px;
    color: #fff;
    background-color: yellowgreen;
   }
 
  </style>
 </head>
 
 <body>
  <div></div>
  <input type="button" value="移动到200" />
 
 
  <script type="text/javascript">
   // 获取到元素(这里有个小细节,如果给元素设置了id名,即便不使用获取元素的方法,也能通过这个id名获取到元素哦~~大家可以自己尝试一下)
   var btn = document.querySelector(&#39;input&#39;),
     dv = document.querySelector(&#39;div&#39;);
   // 添加点击事件
   btn.addEventListener(&#39;click&#39;,function() {
    var timer = null,// 保存定时器
      currentDistance = dv.offsetLeft, // 当前离父盒子的距离
      step = 8,// 每次改变的距离
      target = 200;// 目标距离
    timer = setInterval(function() {
     currentDistance += step;// 当前距离 = 上一个当前距离 + 改变的距离
     if((target - currentDistance) < step) { 
      currentDistance = target; // 如果目标距离与当前距离的差小于了要改变的距离,这时候我们就直接让当前距离等于目标距离,防止盒子停下来的时候有误差
      clearInterval(timer); // 清楚定时器
      timer = null; // 将timer解绑,释放内存
     }
     dv.style.left = currentDistance + &#39;px&#39;; // 最核心的一步,改变盒子的left为当前距离
    },17)
   })
  </script>
 </body>
</html>

2. 예비 이동 효과가 달성된 후 요구 사항을 개선합니다.

상자가 200px 위치로 이동한 후, 상자가 400px 위치로 계속 이동하기를 원합니까?

분석:

1) 이때 클릭할 수 있는 버튼은 2개입니다. 하나는 200px로 이동하고, 다른 하나는 400px로 이동합니다

2). 두 개의 움직임이지만 그들이 사용하는 기능은 동일하며 한 지점에서 다른 지점으로 이동하므로 재사용을 위해 1의 움직임을 함수로 캡슐화하는 것을 고려합니다.

코드~ 

rree

3. 상자가 앞뒤로 움직이는 기능을 캡슐화했지만 캐러셀의 스크롤 효과를 다시 생각해 보겠습니다. 그러나 처음에는 매우 뭉툭하고 롤링이 완료될수록 속도는 점차 감소합니다.

요구사항: 박스 이징(즉, 가변 속도 이동)

코드 업로드~ 

<!DOCTYPE html>
<html>
<head>
 <meta charset="UTF-8" />
 <title>Document</title>
 <style type="text/css">
 * {
  margin: 0;
  padding: 0;
 }
 div {
  position: absolute;
  top: 50px;
  width: 100px;
  height: 100px;
  background-color: red;
 }
 input {
  width: 100px;
  height: 30px;
  color: #fff;
  background-color: yellowgreen;
 }
 
 </style>
</head>
 
<body>
 <div></div>
 <input type="button" value="移动到200" />
 <input type="button" value="移动到400" />
 <script type="text/javascript">
 // 封装函数,盒子和目标距离都是不确定的,我们可以将他们作为参数传递。
 function animation(tag,target) {
  var timer = null,
   currentDistance = tag.offsetLeft,
   step = 5;
  step = currentDistance < target? step: -step;// 判断step的正负,200到400时是递增,400到200时是递减
  timer = setInterval(function() {
  if(Math.abs(currentDistance - target) > Math.abs(step)) { // 这里判断条件也要略作改动,使用绝对值进行比较
   currentDistance += step; /
   tag.style.left = currentDistance + &#39;px&#39;;
  }else {
   tag.style.left = target + &#39;px&#39; // 当当前距离与目标距离之间的差值小于step改变的距离时,我们直接让盒子移动到目标距离。
   clearInterval(timer);
   timer = null;
  }
  },17)
 }
 var btns = document.querySelectorAll(&#39;input&#39;),
  dv = document.querySelector(&#39;div&#39;);
 btns[0].addEventListener(&#39;click&#39;,function() {
  animation(dv,200);
 })
 btns[1].addEventListener(&#39;click&#39;,function() {
  animation(dv,400);
 })
 </script>
</body>
</html>

자, 캐러셀 차트에 필요한 가장 기본적인 이징 기능은 다음과 같습니다. 완료 ~

여기에 더 완전한 완화 기능이 있습니다. 더 포괄적인 기능을 갖고 있으며 동시에 여러 스타일을 변경할 수 있습니다.

function animation(tag,target) {
  var timer = null;
  timer = setInterval(function() {
  var currentDistance = tag.offsetLeft,
   step = (target - currentDistance) / 5;// 通过目标距离与当前距离的差除以5便达到了我们需要的变速运动,因为step每次定制器执行都要改变,所以放入定时器内
  step = step > 0 ? Math.ceil(step):Math.floor(step);// 这里如果将currentDistance定时器外面声明可以不用写,如果放在定时器内声明,因为offsetLeft取整的特性,要对step进行取整
  if(Math.abs(currentDistance - target) > Math.abs(step)) {
   currentDistance += step;
   tag.style.left = currentDistance + &#39;px&#39;;
  }else {
   tag.style.left = target + &#39;px&#39;
   clearInterval(timer);
   timer = null;
  }
  },17)
rrree

위 내용은 이 글의 전체 내용입니다. 모든 분들의 학습에 도움이 되기를 바랍니다. 또한 모든 분들이 PHP 중국어 웹사이트를 지지해 주시길 바랍니다.

JS 캐러셀의 완화 기능 캡슐화와 관련된 더 많은 기사를 보려면 PHP 중국어 웹사이트에 주목하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.