移动端轮播图实现方法(dGun.js)
本文章介绍在移动端无缝隙轮播图实现的原理,这个轮子比较简单,但可以方便刚刚入门的同学参考。最终效果是在移动端无缝隙无限滑动,可以自定义轮播的速度。支持手势左右滑动。最后会放上源码。
- HTML部分
<div class="outer" id="oneTest">
<div class="inner">
<div class="goIndex item" goUrl="https://www.baidu.com"
style="background-image:url(1.jpg)"></div>
<div class="goIndex item" goUrl="https://www.baidu.com"
style="background-image:url(2.jpg)"></div>
<div class="goIndex item" goUrl="https://www.baidu.com"
style="background-image:url(3.jpg)"></div>
</div>
<ul class="num"></ul>
</div>
轮播图的html就是这样,我们配合着css来看,接下来上css。
- Css部分
* {
margin: 0;
padding: 0;
}
ul {
list-style: none;
}
.outer {
margin: 0 auto;
width: 100%;
height: 150px;
overflow: hidden;
position: relative;
}
.inner {
height: 150px;
overflow: hidden;
width: 8000px;
}
.inner .goIndex {
float: left;
height: 150px;
background-repeat: no-repeat;
background-position: center center;
background-size: cover;
}
.num {
position: absolute;
left: 0;
right: 0;
bottom: 20%;
display: flex;
justify-content: center;
flex-direction: row;
align-items: center;
}
.num li {
margin: 0 3px;
width: 8px;
height: 8px;
border-radius: 50%;
background: rgba(0, 0, 0, .2);
}
.num li.select {
background: rgba(0, 0, 0, .7);
}
我们通过css可以看到,.outer为最外层的壳,超出的部分都会隐藏,.inner为一个很长很长的容器,而item为单个item。结构比较简单。ul就是小的控制点了,但移动端没有点击小点的功能。
- 页面中Js部分
//function dGun(obj = {}) 这是dGun.js的主函数
// 初始化两个图片轮播
dGun({id:"oneTest",time:10000});
dGun({id:"twoTest",time:4000});
// 点击后跳转
var goList = document.getElementsByClassName("goIndex");
for (var i = 0; i < goList.length; i++) {
goList[i].addEventListener("click", function () {
window.location = this.getAttribute("goUrl")
})
}
dGun()就是初始化轮播图我们需要传入参数,第一个参数id为.outer盒子的id,第二个为自动切换时间。下面的是简单的点击跳转功能。
- dGun.js 初始化部分
//function dGun(obj = {}) 包裹全部dGun内代码
var id = obj.id; //获取domid
var time = obj.time ? parseInt(obj.time) : 3000; //默认3s
time = time > 300 ? time : 1000; //间隔必须大于300
var _width = document.querySelector("#"+id).offsetWidth; //获取轮播图宽度
var _index = 0; //当前是第几个轮播 从-1开始
var inner = document.querySelector("#"+id+" .inner"); //获取轮播内容外壳(很长的那个)
var items = document.querySelectorAll("#"+id+" .item"); //获取轮播元素
// 将第一个元素复制到最后,将最后的元素复制到开头
var firstItem = items[0];
var lastItem = items[items.length-1];
inner.insertBefore(lastItem.cloneNode(true),firstItem);
inner.appendChild(firstItem.cloneNode(true));
inner.style.transform = "translateX(-"+_width+"px)";
// 生成底部小圆点
var imgLength = document.querySelector("#"+id+" .inner").children.length-2;
var makeCir = '<li class="select"></li>';
for (var i = 0; i < imgLength - 1; i++) {
makeCir += '<li></li>';
}
document.querySelector("#"+id+" .num" ).innerHTML = makeCir;
//设置轮播的宽度。
var newItems = document.querySelectorAll("#"+id+" .item");
for(var i = 0; i<newItems.length;i++){
newItems[i].style.width = _width+"px";
}
前几行代码就不多介绍了,就是获取dom,获取宽度。
这里说一下将第一个元素复制到最后,将最后的元素复制到开头,这是实现无缝隙的关键,比如我们有3张图片1/2/3进行轮播,这样我们就需要将dom节点变为3/1/2/3/1,为什么这样做呢,轮播图原理是多个item并列,我们通过translateX进行值的改变显示不同区域,我们先将dom节点变为3/1/2/3/1,然后通过inner.style.transform = "translateX(-"+_width+"px)";这句代码将初始化轮播显示区域放到1这个图片上。然后人们向右滑动,滑动到3的时候,再向右滑应该显示1,而我们dom节点中3的右边就是1,这样向右滑动到末尾1的时候我们快速通过translateX移动到开头1的位置来实现无缝隙轮播。
- 手势滑动实现
var startX = 0, changedX = 0, originX = 0, basKey = 0;
//手指点击的X位置 滑动改变X的位置 inner的translateX的值 basKey是个钥匙
function Broadcast() {
var that = this;
this.box = document.querySelector("#"+id+" .inner");
this.box.addEventListener("touchstart", function (ev) {
that.fnStart(ev);
})
}
// 轮播手指按下
Broadcast.prototype.fnStart = function (ev) {
clearInterval(autoPlay); //手指按下的时候清除定时轮播
if (!basKey) {
var that = this;
startX = ev.targetTouches[0].clientX;
var tempArr = window.getComputedStyle(inner).transform.split(",");
//获取当前偏移量
if (tempArr.length > 2) {
originX = parseInt(tempArr[tempArr.length - 2]) || 0;
}
this.box.ontouchmove = function (ev) {
that.fnMove(ev)
}
this.box.ontouchend = function (ev) {
that.fnEnd(ev)
}
}
};
// 轮播手指移动
Broadcast.prototype.fnMove = function (ev) {
ev.preventDefault();
changedX = ev.touches[0].clientX - startX;
var changNum = (originX + changedX);
this.box.style.cssText = "transform: translateX(" + changNum + "px);";
};
// 轮播手指抬起
Broadcast.prototype.fnEnd = function (ev) {
// 移除底部按钮样式
document.querySelector("#"+id+" .select").classList.remove("select");
basKey = 1;
setTimeout(function () {
basKey = 0;
}, 300)
if (changedX >= 100) { //向某一方向滑动
var _end = (originX + _width);
this.box.style.cssText = "transform: translateX(" + _end + "px);transition:all .3s";
_index--;
if (_index == -1) { //滑动到第一个了,为了实现无缝隙,滚到最后去
document.querySelectorAll("#"+id+" .num>li")[imgLength - 1].classList.add("select");
play(-1);
}
} else if (changedX < -100) { //向负的某一方向滑动
var _end = (originX - _width);
this.box.style.cssText = "transform: translateX(" + _end + "px);transition:all .3s";
_index++;
if (_index == imgLength) { //滑到最后一个了,为了实现无缝隙,滚到前面去
play(imgLength);
document.querySelectorAll("#"+id+" .num>li")[0].classList.add("select");
}
} else { //滑动距离太短,没吃饭不用管
this.box.style.cssText = "transform: translateX(" + originX + "px);transition:all .3s";
}
// 完成一次滑动初始化值
startX = 0;
changedX = 0;
originX = 0;
if (_index != -1 && _index != imgLength) {
document.querySelectorAll("#"+id+" .num>li")[_index].classList.add("select");
}
this.box.ontouchmove = null; //清除事件
this.box.ontouchend = null; //清除绑定事件
autoPlay = setInterval(lunbo, time) //开启轮播
}
我们定义Broadcast方法监听用户的触屏按下事件
当手指按下时,我么记录手指按下的X轴位置,单后进行监听移动和抬起的事件。
手指移动的时候我们要做到就是计算偏移量,并通过偏移量改变inner的位置。
手指抬起时,我们查看偏移量十分大于100,这个值可以改,也可以改一下变成传参。通过正负判断方向,并通过index判断当前是第几个,如果是滑动到我们复制的第一个和最后一个节点,则执行play函数,我们接下来讲解。然后改变控制点样式就比较简单了,最后初始化值,并清除监听事件。
- play函数,快速滚
//首尾无缝连接
function play(index) {
setTimeout(function () {
inner.style.transition = 'all 0s';
if (index == -1) {
var _number = -imgLength * _width;
inner.style.transform = 'translateX(' + _number + 'px)';
_index = imgLength - 1;
} else if (index == imgLength) {
inner.style.transform = 'translateX(-' + _width + 'px)';
_index = 0;
}
}, 250);
}
原理就是在图片滑动完成的时候,快速设置滑动变化时间设为0,并改变translateX到应该去的位置。
- 定时切换图片
function lunbo(){
document.querySelector("#"+id+" .select").classList.remove("select");
var tempArr = window.getComputedStyle(inner).transform.split(",");
if (tempArr.length > 2) {
originX = parseInt(tempArr[tempArr.length - 2]) || 0;
}
var _end = (originX - _width);
inner.style.cssText = "transform: translateX(" + _end + "px);transition:all .3s";
_index++;
if (_index != -1 && _index != imgLength) {
document.querySelectorAll("#"+id+" .num>li")[_index].classList.add("select");
}else if(_index == -1 ){
document.querySelectorAll("#"+id+" .num>li")[imgLength - 1].classList.add("select");
} else if (_index == imgLength) {
play(imgLength);
document.querySelectorAll("#"+id+" .num>li")[0].classList.add("select");
}
}
// 初始化轮播
var autoPlay = setInterval(lunbo,time); //开启轮播
var _Broadcast = new Broadcast(); //实例触摸
这个就是开启个定时器,过固定的时间偏移inner的X,并根据是第几个来判断是否要执行play函数。
- https://github.com/Zhoujiando... 源码在这里面,大家可以看一下,萌新如果感觉有帮助麻烦点下Star 点奇数次就好。 本人刚入行不久,大神们看着不顺眼的地方麻烦提提意见,谢谢。最后提前给大家拜个早年。
移动端轮播图实现方法(dGun.js)的更多相关文章
- 原生js实现简单移动端轮播图
最近项目不是很忙,自己就用原生js写了一个简单的移动端轮播图的小demo,可实现自动轮播和手势滑动轮播,然后就把它记录到个人博客里.还有很多不足的地方,希望多多指出,以便改进. 1.代码部分 分为四个 ...
- 告别组件之教你使用原生js和css写移动端轮播图
在工作中由于项目需要要写一个轮播图,本想使用组件直接调用实现快速开发,但是一想到自己经常使用组件但是让自己手写的话确实一点都不会. 一个不会手写组件的前端程序员不是一个好程序员!于是打算自己手写一个. ...
- 移动端轮播图vue-awesome-swiper
日常写设计文档,日常写Demo,写轮播图的时候觉得bootstrap不适合移动端,或者说不是轻量级的,于是换成Swiper,但是写的时候才发现怎么把这东西嵌到Vue里面啊? Σ( ° △ °|||)︴ ...
- 原生JS实现移动端轮播图
功能描述: 自动无缝轮播图片,底部小圆点跟图片保持一致:手指左右移动轮播图,移动距离大于50px播放下一张(或上一张),小于50px则回弹 具体功能实现: 1.定时器 自动轮播图片 先声明一个inde ...
- 关于Layui 响应式移动端轮播图的问题
用layui做轮播图,在手机上宽度异常, 可通过以下方法解决, 不喜欢layui的同学可以选择Swiper // 轮播图 layui.use('carousel', function () { var ...
- H5制作显示轮播图的方法Swiper
1.需要引入Swiper插件 <!-- swiper插件 --> <link rel="stylesheet" href="https://unpkg. ...
- PC 端轮播图的实现
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8& ...
- 纯js轮播图练习-2,js+css旋转木马层叠轮播
基于css3的新属性,加上js的操作,让现在js轮播图花样越来越多. 而现在出现的旋转木马层叠轮播的轮播图样式,却是得到了很多人都喜爱和投入使用. 尤其是在各大软件中,频繁的出现在大家的眼里,在web ...
- JS 移动端轮播图案例
body { margin:; } .hearder { width: 100%; height: 150px; position: relative; } ul { list-style: none ...
随机推荐
- token和refresh token
https://www.cnblogs.com/minirice/p/9232355.html 在spring boot中结合OAuth2使用JWT时,刷新token时refresh token一直变 ...
- 68.26-95.44-99.74 rule|empirical rule
6.3 Working with Normally Distributed Variables As illustrated in the previous example, the 68.26-95 ...
- cnn可视化 感受野(receptive field)可视化
网址: https://befreeroad.github.io/#/editor 参考: http://ethereon.github.io/netscope/#/editor 在此基础上添加 感受 ...
- Exchange Onine功能介绍
Exchange Online是Office 365中提供的一个邮箱服务.Microsoft Exchange Online是将Microsoft Exchange Server功能作为基于云的服务提 ...
- springboot学习笔记:11.springboot+shiro+mysql+mybatis(通用mapper)+freemarker+ztree+layui实现通用的java后台管理系统(权限管理+用户管理+菜单管理)
一.前言 经过前10篇文章,我们已经可以快速搭建一个springboot的web项目: 今天,我们在上一节基础上继续集成shiro框架,实现一个可以通用的后台管理系统:包括用户管理,角色管理,菜单管理 ...
- openpyxl传入表名时不要使用默认的sheet表名
openpyxl传入表名时不要使用默认的sheet表名,会报错 处理:改一下表名即可
- proxmox新版本使用了lxc容器,导致以前的vzlist命令无法使用,于是自己写了一个脚本来获取所有半虚拟化主机的信息状态
#!/usr/bin/env python #encoding:utf-8 # desc:用来描述各个主机信息 import os #CTID NPROC STATUS IP_ADDR HOSTNAM ...
- leetcode第30题:括号生成
这是目前遇到最难的题,刚开始的思路是:匹配words中元素是否在s中,若在找所在元素的后words长度位的字符串,判断words其他元素是否都在s中. 看似这个思路可行,实际上存在的问题: 1.wor ...
- python3下scrapy爬虫(第一卷:安装问题)
一般爬虫都是用urllib包,requests包 配合正则.beautifulsoup等包混合使用,达到爬虫效果,不过有框架谁还用原生啊,现在我们来谈谈SCRAPY框架爬虫, 现在python3的兼容 ...
- [LC] 230. Kth Smallest Element in a BST
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Not ...