原生JS轮播图插件


Posted in Javascript onFebruary 09, 2017

代码分两个部分:1、HTML部分,根据注释处理即可;2、play.js插件部分,引到HTML里面即可。

1、HTML部分:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
  <style>/*style标签及其内的内容,在实际项目中可以不要*/
    * {
      margin: 0;
      padding: 0;
    }
  </style>
</head>
<body>
<!--body标签里的内容,没说可以增减或更改的,不要增减或更改-->
<div id="box">
  <div>
    <!--以下是可增减区域-->
    <div><img src="img/banner1.jpg" alt=""/></div>
    <div><img src="img/banner2.jpg" alt=""/></div>
    <div><img src="img/banner3.jpg" alt=""/></div>
    <div><img src="img/banner4.jpg" alt=""/></div>
    <div><img src="img/banner5.jpg" alt=""/></div>
    <div><img src="img/banner6.jpg" alt=""/></div>
    <div><img src="img/banner7.jpg" alt=""/></div>
    <!--以上是可增减区域-->
  </div>
</div>
<script src="play.js"></script>
<script>
  var play= new Banner('1000px', '500px');
  /*这两个参数分别是轮播区的宽和高,可以根据需要更改*/
</script>
</body>
</html>

2、play.js插件部分

function Banner(width, height) {/*类*/
  /*以下最外层div*/
  var that = this;
  this.width = width;
  this.height = height;
  this.oBox = document.getElementById("box");
  this.oBox.style.width = width;
  this.oBox.style.height = height;
  this.oBox.style.margin = "0 auto";
  this.oBox.style.overflow = "hidden";
  this.oBox.style.position = "relative";
  /*以下轮播区的div*/
  this.oBoxInner = this.oBox.getElementsByTagName('div')[0];
  this.oBoxInner.style.height = height;
  this.oBoxInner.style.position = "absolute";
  this.oBoxInner.style.left = 0;
  this.oBoxInner.style.right = 0;
  this.aDiv = this.oBoxInner.getElementsByTagName('div');//单个轮播图
  this.oBoxInner.innerHTML/* 轮播区的内部后面*/ += this.aDiv[0].outerHTML/*第一个轮播图片的外部*/;
  this.oBoxInner.style.width = parseFloat(width) * this.aDiv.length + "px";//轮播区的宽度
  for (var i = 0; i < this.aDiv.length; i++) {/*遍历轮播区的每个div及其内部的图片*/
    this.aDiv[i].style.width = width;
    this.aDiv[i].style.height = height;
    this.aDiv[i].style.float = "left";
    this.aDiv[i].aImg = this.aDiv[i].getElementsByTagName('img')[0];
    this.aDiv[i].aImg.style.width = "100%";
    this.aDiv[i].aImg.style.height = "100%";
  }
  /*以下是焦点区部分(定位在轮播区的右下方)*/
  var oUl=document.createElement('ul');
  for(i=0; i<this.aDiv.length-1; i++){
    oUl.innerHTML+='<li class='+i+'===1?"on":null></li>';
  }
  this.oBox.appendChild(oUl);
  this.oUl = this.oBox.getElementsByTagName('ul')[0];
  this.oUl.style.position = "absolute";
  this.oUl.style.right = "10px";
  this.oUl.style.bottom = "10px";
  this.aLi = this.oUl.getElementsByTagName('li');
  for (i = 0; i < this.aLi.length; i++) {/*遍历焦点区的每个焦点*/
    this.aLi[i].style.width = "18px";
    this.aLi[i].style.height = "18px";
    this.aLi[i].style.float = "left";
    this.aLi[i].style.listStyle = "none";
    this.aLi[i].style.background = "green";
    this.aLi[i].style.borderRadius = "50%";
    this.aLi[i].style.marginLeft = "10px";
    this.aLi[i].style.cursor = "pointer";
  }
  /*以下是向左向右两个箭头式按钮*/
  for(i=0; i<2; i++){
    var oA=document.createElement('a');
    oA.href="javascript:;" rel="external nofollow" 
    this.oBox.appendChild(oA);
  }
  /*以下是左按钮(点击它,图片向左运动)*/
  this.oBtnL = this.oBox.getElementsByTagName('a')[0];
  this.oBtnL.style.width = "30px";
  this.oBtnL.style.height = "30px";
  this.oBtnL.style.position = "absolute";
  this.oBtnL.style.top = (parseFloat(this.height) / 2 - 15) + "px";
  this.oBtnL.style.left = "30px";
  this.oBtnL.style.border = "10px solid red";
  this.oBtnL.style.borderLeft = "none";
  this.oBtnL.style.borderBottom = "none";
  this.oBtnL.style.opacity = "0.3";
  this.oBtnL.style.filter = "alpha(opacity=30)";
  this.oBtnL.style.display = "none";
  this.oBtnL.style.transform = "rotate(-135deg)";
  this.oBtnL.onclick = function () {
    if (that.step <= 0) {
      that.step = that.aDiv.length - 1;
      that.css(that.oBoxInner, 'left', -that.step * parseFloat(that.width));
    }
    that.step--;
    that.animate(that.oBoxInner, {left: -that.step * parseFloat(that.width)});
    that.bannerTip();
  };
  /*以下是右按钮(点击它,图片向右运动)*/
  this.oBtnR = this.oBox.getElementsByTagName('a')[1];
  this.oBtnR.style.width = "30px";
  this.oBtnR.style.height = "30px";
  this.oBtnR.style.position = "absolute";
  this.oBtnR.style.top = (parseFloat(this.height) / 2 - 15) + "px";
  this.oBtnR.style.right = "30px";
  this.oBtnR.style.border = "10px solid red";
  this.oBtnR.style.borderLeft = "none";
  this.oBtnR.style.borderBottom = "none";
  this.oBtnR.style.opacity = "0.3";
  this.oBtnR.style.filter = "alpha(opacity=30)";
  this.oBtnR.style.display = "none";
  this.oBtnR.style.transform = "rotate(45deg)";
  this.oBtnR.onclick = function () {
    if (that.step >= that.aDiv.length - 1) {
      that.step = 0;
      that.css(that.oBoxInner, 'left', 0)
    }
    that.step++;
    that.animate(that.oBoxInner, {left: -that.step * parseFloat(that.width)}, 1000);
    that.bannerTip();
  };
  /*以下是其它*/
  this.step = 0;//记录每次运动
  this.timer = null;//定时器
  this.init();//初始化轮播图
}
Banner.prototype = {//类的原型
  constructor: Banner,
  /*getCss:获取元素的属性值*/
  getCss: function (curEle, attr) {
    var val = null;
    var reg = null;
    if (getComputedStyle) {//标准浏览器
      val = getComputedStyle(curEle, false)[attr];
    } else {//非标准浏览器
      if (attr === 'opacity') {
        val = curEle.currentStyle.filter; //'alpha(opacity=10)'
        reg = /^alpha\(opacity[=:](\d+)\)$/i;
        return reg.test(val) ? reg.exec(val)[1] / 100 : 1;
      }
      val = curEle.currentStyle[attr];
    }
    reg = /^[+-]?((\d|([1-9]\d+))(\.\d+)?)(px|pt|rem|em)$/i;
    return reg.test(val) ? parseInt(val) : val;
  },
  /*setCss:设置元素的属性值*/
  setCss: function (curEle, attr, value) {
    if (attr === 'float') {
      curEle.style.cssFloat = value;
      curEle.style.styleFloat = value;
      return;
    }
    if (attr === 'opacity') {
      curEle.style.opacity = value;
      curEle.style.filter = 'alpha(opacity=' + (value * 100) + ')';
      return;
    }
    var reg = /^(width|height|top|right|bottom|left|((margin|padding)(top|right|bottom|left)?))$/i;
    if (reg.test(attr)) {
      if (!(value === 'auto' || value.toString().indexOf('%') !== -1)) {
        value = parseFloat(value) + 'px';
      }
    }
    curEle.style[attr] = value;
  },
  /*setGroupCss:设置元素的一组属性值*/
  setGroupCss: function (curEle, options) {
    if (options.toString() !== '[object Object]') return;
    for (var attr in options) {
      this.setCss(curEle, attr, options[attr]);
    }
  },
  /*css:getCss、setCss、setGroupCss的合写*/
  css: function () {
    if (typeof arguments[1] === 'string') {
      if (typeof arguments[2] === 'undefined') {
        return this.getCss(arguments[0], arguments[1]);//当第三个参数不存在,是获取;
      } else {
        this.setCss(arguments[0], arguments[1], arguments[2]);//当第三个参数存在时,是设置;
      }
    }
    if (arguments[1].toString() === '[object Object]') {
      this.setGroupCss(arguments[0], arguments[1]);//设置元素的一组属性值
    }
  },
  /*animate:轮播图动画函数*/
  animate: function (curEle, target, duration) {
    /*1.定义动画的运行轨迹*/
    function tmpEffect(t, b, c, d) {
      return b + c / d * t;//开始时的位置+总变化/总时间*已经过去的时间
    }
    /*2.为公式的每个参数做准备*/
    var begin = {};
    var change = {};
    for (var attr in target) {
      begin[attr] = this.css(curEle, attr);
      change[attr] = target[attr] - begin[attr];
    }
    duration = duration || 700;
    var time = 0;
    var that = this;
    /*3.开启一个定时器,让时间不断累加;根据时间和公式,求出最新的位置;*/
    clearInterval(curEle.timer); //开起一个定时器前,先关闭没用的定时器
    curEle.timer = setInterval(function () {
      time += 10;
      /*4.定时器停止运动的条件(time>=duration)*/
      if (time >= duration) {
        that.css(curEle, target);
        clearInterval(curEle.timer);
        return;
      }
      /*5.拿到每个属性的最新值,并且赋值给元素对应的属性;*/
      for (var attr in target) {
        var curPos = tmpEffect(time, begin[attr], change[attr], duration);
        that.css(curEle, attr, curPos);
      }
    }, 10)
  },
  /*初始化轮播图*/
  init: function () {
    var _this = this;
    /*1.开启自动轮播*/
    this.timer = setInterval(function () {
      _this.autoMove();
    }, 2000);
    /*2.开启焦点,每个焦点与每张轮播图对应*/
    this.bannerTip();
    /*3.鼠标移入轮播区,轮播暂停;鼠标移出轮播区,轮播恢复*/
    this.over_out();
    /*4.点击焦点,响应对应的轮播图片*/
    this.handleChange();
  },
  handleChange: function () {
    for (var i = 0; i < this.aLi.length; i++) {
      this.aLi[i].index = i;
      var that = this;
      this.aLi[i].onclick = function () {
        that.step = this.index;
        that.animate(that.oBoxInner, {left: -that.step * parseFloat(that.width)});
        that.bannerTip();
      }
    }
  },
  autoMove: function () {
    if (this.step >= this.aDiv.length - 1) {
      this.step = 0;
      this.css(this.oBoxInner, 'left', 0)
    }
    this.step++;
    this.animate(this.oBoxInner, {left: -this.step * parseFloat(this.width)}, 1000);
    this.bannerTip();
  },
  bannerTip: function () {
    var tmpStep = this.step >= this.aLi.length ? 0 : this.step;
    for (var i = 0; i < this.aLi.length; i++) {
      this.aLi[i].className = i === tmpStep ? 'on' : null;
      if (this.aLi[i].className === "on") {
        this.aLi[i].style.background = "red";
      } else {
        this.aLi[i].style.background = "green";
      }
    }
  },
  over_out: function () {
    var _this = this;
    _this.oBox.onmouseover = function () {
      clearInterval(_this.timer);
      _this.oBtnL.style.display = 'block';
      _this.oBtnR.style.display = 'block';
    };
    _this.oBox.onmouseout = function () {
      _this.timer = setInterval(function () {
        _this.autoMove()
      }, 2000);
      _this.oBtnL.style.display = 'none';
      _this.oBtnR.style.display = 'none';
    }
  }
};

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持三水点靠木!

Javascript 相关文章推荐
Javascript基础教程之if条件语句
Jan 18 Javascript
避免jQuery名字冲突 noConflict()方法
Jul 30 Javascript
js 事件的传播机制(实例讲解)
Jul 20 Javascript
使用JQuery实现图片轮播效果的实例(推荐)
Oct 24 jQuery
Vue2.0 实现歌手列表滚动及右侧快速入口功能
Aug 08 Javascript
详解小程序中h5页面onShow实现及跨页面通信方案
May 30 Javascript
js遍历详解(forEach, map, for, for...in, for...of)
Aug 28 Javascript
ES6 Promise对象概念及用法实例详解
Oct 15 Javascript
JavaScript简易计算器制作
Jan 17 Javascript
浅谈webpack构建工具配置和常用插件总结
May 11 Javascript
Vue基于iview table展示图片实现点击放大
Aug 05 Javascript
用JavaScript实现贪吃蛇游戏
Oct 23 Javascript
jQuery页面弹出框实现文件上传
Feb 09 #Javascript
如何在Angular2中使用jQuery及其插件的方法
Feb 09 #Javascript
详解angular2采用自定义指令(Directive)方式加载jquery插件
Feb 09 #Javascript
vue-router跳转页面的方法
Feb 09 #Javascript
基于JavaScript实现复选框的全选和取消全选
Feb 09 #Javascript
jquery.cookie.js的介绍与使用方法
Feb 09 #Javascript
js 数据存储和DOM编程
Feb 09 #Javascript
You might like
PHP导出EXCEL快速开发指南--PHPEXCEL的使用详解
2013/06/03 PHP
PHP使用stream_context_create()模拟POST/GET请求的方法
2016/04/02 PHP
PHP 实现页面静态化的几种方法
2017/07/23 PHP
PHP编程实现计算抽奖概率算法完整实例
2017/08/09 PHP
PHP实现的微信公众号扫码模拟登录功能示例
2019/05/30 PHP
laravel-admin 在列表页添加自定义按钮的例子
2019/09/30 PHP
javascript之对系统的toFixed()方法的修正
2007/05/08 Javascript
认识延迟时间为0的setTimeout
2008/05/16 Javascript
JavaScript中常见陷阱小结
2010/04/27 Javascript
jQuery中调用WebService方法小结
2011/03/28 Javascript
JavaScript保留两位小数的2个自定义函数
2014/05/05 Javascript
js实现仿Discuz文本框弹出层效果
2015/08/13 Javascript
jquery实现移动端点击图片查看大图特效
2020/09/11 Javascript
input获取焦点时底部菜单被顶上来问题的解决办法
2017/01/24 Javascript
详解nodejs express下使用redis管理session
2017/04/24 NodeJs
微信小程序实现传参数的几种方法示例
2018/01/10 Javascript
vue 路由页面之间实现用手指进行滑动的方法
2018/02/23 Javascript
详解Vue项目中出现Loading chunk {n} failed问题的解决方法
2018/09/14 Javascript
详解vuejs2.0 select 动态绑定下拉框支持多选
2019/04/25 Javascript
vue实现购物车的监听
2020/04/20 Javascript
[59:42]Secret vs Alliacne 2019国际邀请赛小组赛 BO2 第一场 8.15
2019/08/17 DOTA
Python实现解析Bit Torrent种子文件内容的方法
2017/08/29 Python
Python算法输出1-9数组形成的结果为100的所有运算式
2017/11/03 Python
数据清洗--DataFrame中的空值处理方法
2018/07/03 Python
opencv python 傅里叶变换的使用
2018/07/21 Python
pandas中apply和transform方法的性能比较及区别介绍
2018/10/30 Python
详解Python3除法之真除法、截断除法和下取整对比
2019/05/23 Python
Python参数类型以及常见的坑详解
2019/07/08 Python
wxPython实现带颜色的进度条
2019/11/19 Python
Python实现图像去噪方式(中值去噪和均值去噪)
2019/12/18 Python
基于django2.2连oracle11g解决版本冲突的问题
2020/07/02 Python
以工厂直接定价的传奇性能:Ben Hogan Golf
2019/01/04 全球购物
食品厂厂长岗位职责
2014/01/30 职场文书
煤矿安全生产责任书
2014/04/15 职场文书
移交协议书
2014/08/19 职场文书
2015年宣传工作总结
2015/04/08 职场文书