>  기사  >  웹 프론트엔드  >  네이티브 js를 사용하여 캐러셀 효과를 구현하기 위한 코드 공유

네이티브 js를 사용하여 캐러셀 효과를 구현하기 위한 코드 공유

零下一度
零下一度원래의
2017-05-19 09:16:521592검색

이 글에서는 기본 js 캐러셀 효과를 구체적으로 소개하고, 간단하고 실용적인 코드를 관심 있는 친구들이 참고할 수 있습니다.

프론트엔드 엔지니어로서, 필기 캐러셀은 마스터하기 위한 가장 기본적인 기술입니다. 다음은 제가 네이티브 js로 작성한 캐러셀입니다. 댓글과 비평을 환영합니다.

첫 번째 CSS 코드

a{text-decoration:none;color:#3DBBF5;}
   *{
    margin: 0;
    padding: 0;
   }
   .wrapper{
    width: 400px;
    height: 300px;
    margin: 100px auto;
   }
   #lunbo{
    position: relative;
    overflow: hidden;
   }
   #list{
    position: relative;
    white-space: nowrap; // 这块用行元素模拟,所以才用该属性,块元素可修改这块
   }
   #list span{
    display: inline-block;
    width: 400px;
    height: 300px;
    text-align: center;
    line-height: 300px;
    font-weight: bold;
    font-size: 100px;
    color: #fff;
   }
   #buttons{
    position: absolute;
    bottom: 0;
    text-align: center;
    width: 100%;
    height: 40px;
    line-height: 40px;
   }
   #buttons span{
    display: inline-block;
    width: 15px;
    height: 5px;
    background: #fff;
    margin: 0 10px;
    cursor: pointer;
    transition: all .5s;
   }
   #buttons span.on{
    height: 20px;
   }
   .arrow{
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    font-size: 80px;
    font-weight: bold;
    color: #fff;
    opacity: .3;
    transition: all .5s;
   }
   .wrapper:hover .arrow{
    opacity: 1;
   }
   #prev{
    left: 10px;
   }
   #next{
    right: 10px;
   }

그럼 HTML 코드

<p class="wrapper">
   <p id="lunbo">
    <p id="list" style="left: -400px;">
     <span style="background:yellow;">5</span><span style="background: red;">1</span><span style="background:black;">2</span><span style="background:green;">3</span><span style="background:blue;">4</span><span style="background:yellow;">5</span><span style="background: red;">1</span>
    </p>
    <p id="buttons">
     <span index="1" class="on"></span>
     <span index="2"></span>
     <span index="3"></span>
     <span index="4"></span>
     <span index="5"></span>
    </p>
    <a href="javascript:;" id="prev" class="arrow"><</a>
    <a href="javascript:;" id="next" class="arrow">></a>
   </p>
  </p>

드디어 js 코드

window.onload=function () {
   var lunBo = document.getElementById("lunbo");
   var list = document.getElementById("list");
   var btn = document.getElementById("buttons").getElementsByTagName(&#39;span&#39;);
   var prev = document.getElementById("prev");
   var next = document.getElementById(&#39;next&#39;);
   var interval = 3000;
   var timer;
   var index = 1;
   var animated = false;
   for (var i=0;i<btn.length;i++) { //按钮加点击事件
    btn[i].onclick=function () {
     if(this.className==&#39;on&#39;) //如果是状态按钮直接返回节约资源
     {
      return
     };
     var myIndex =parseInt(this.getAttribute(&#39;index&#39;));//获取按钮的index属性值
     var offset = -400*(myIndex-index); //根据属性值 计算偏移量
     animate(offset)  //轮播动画
     index = myIndex; // 改变索引值
     showBtn();   //显示状态按钮
    }
   }
   function showBtn () { 
    for (var i=0;i<btn.length;i++) {
     btn[i].className=&#39;&#39;; 
    }
    btn[index-1].className=&#39;on&#39;;
   }
   prev.onclick=function () { //上一页事件
    if (animated) { //如果是动画状态 直接返回解决bug
     return;
    }
    if (index==1) { 
     index =btn.length;
    } else{
     index-=1;
    }
    animate(400); 
    showBtn();
   }
   next.onclick=function () {
    if (animated) {
     return;
    }
    if (index==btn.length) {
     index =1;
    } else{
     index+=1;
    }
    animate(-400);
    showBtn();
   }
   function animate(offset) {
    animated = true; //表示在动画状态
    var newLeft = parseInt(list.style.left) + offset; //计算新的left值
    var time = 400; //设置动画总时间
    var interval = 10; //动画帧时间
    var speed = offset/(time/interval); //每帧运动距离
    function go () { 
     if ((speed>0 && parseInt(list.style.left)<newLeft) || (speed<0 && parseInt(list.style.left)>newLeft)) { //通过条件判断到它是否还要继续进行动画
      list.style.left = parseInt(list.style.left) + speed +&#39;px&#39;;
      setTimeout(go,interval) 
     } else{
      animated = false; //动画状态结束
      list.style.left = newLeft + &#39;px&#39;; //现在的位移
      if (parseInt(list.style.left)<-2000) { // 辅助假图
       list.style.left = -400 + &#39;px&#39;;
      } else if( parseInt(list.style.left)>-400){
       list.style.left = -2000 + &#39;px&#39;;
      }
     }
    }
    go();
   }
   function play () { 
    timer = setTimeout(function () {
     next.onclick();
     play();
    },interval)
   }
   play();
   function stop () {
    clearTimeout(timer);
   }
   lunBo.onmouseover=stop;
   lunBo.onmouseout=play;
  }

위의 코드는 전부입니다. 조언과 교환을 환영합니다!

[관련 추천]

1. 무료 js 온라인 동영상 튜토리얼

JavaScript 중국어 참조 매뉴얼

3. php.cn Dugu Jiujian (3) - JavaScript 비디오 튜토리얼

위 내용은 네이티브 js를 사용하여 캐러셀 효과를 구현하기 위한 코드 공유의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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