美文网首页Swartz动物园
JavaScript实现轮播图的两种思路

JavaScript实现轮播图的两种思路

作者: Csdoker | 来源:发表于2017-02-04 10:50 被阅读71次

    这里粗略记录一下在项目中轮播图实现的两种思路。

    首先是内容区域的width和height固定,也就是最常见的情况,通常的做法即是先获取到内容部分每个div或者图片左边的距离style.left,然后改变每个区域的style.left(增加或减少特定值,通常是每个部分的width)来实现轮播的效果。

    示例代码:

    
    function animate(offset) {
    
      //获取的是style.left,是相对左边获取距离,所以第一张图后style.left都为负值,
      //且style.left获取的是字符串,需要用parseInt()取整转化为数字。
      var newLeft = parseInt(list.style.left) + offset;
      list.style.left = newLeft + 'px';
    
      //无限滚动判断
      if (newLeft > -958) {
        list.style.left = -4790 + 'px';
      }
    
      if (newLeft < -4790) {
        list.style.left = -958 + 'px';
      }
    }
    
    prev.onclick = function () {
      index -= 1;
    
      if (index < 1) {
        index = 5
      }
    
      animate(958);
    };
    
    next.onclick = function () {
      index += 1;
    
      if (index > 5) {
        index = 1
      }
    
      animate(-958);
    };
    
    

    第二种情况是当内容区域的width和height不固定时,就应该把所有部分(div)看成一个整体,然后改变整体的style.left值,height可以根据浏览器的高度来适配,这样就做到了不同的屏幕分辨率下能自动适配高度。

    示例代码:

    
    var imgHeight = document.getElementById("bannerlist").getElementsByTagName("img")[0].clientHeight;
    document.getElementById("bannerlist").style.height = imgHeight + "px";
    
    function banneranimate(clickIndex) {
      document.getElementById("imgs").style.left = -(clickIndex-1)*100+"%";
    }
    
    

    可以看到其实两种方法的整体思路是一样的,不过在实际的运用当中还需要根据具体情况来改变一些实现的思路。

    相关文章

      网友评论

        本文标题:JavaScript实现轮播图的两种思路

        本文链接:https://www.haomeiwen.com/subject/cwsjittx.html