本文实例为大家分享了JS实现轮播图案例的具体代码,供大家参考,具体内容如下

实现功能:

1、自动轮播:鼠标停留在轮播图上时不切换图片,鼠标离开后自动轮播。

2、点击左右按钮切换图片。

3、点击下方按钮切换到对应的图片。

4、轮播图大小自适应:

可以放入到执行的父容器中展示。

不指定父容器时,默认放入body标签。占满一屏的宽度,当改变浏览器窗口大小时,轮播图大小成比例改变。

可以指定轮播图的宽高。

实现方式:用面向对象的方式实现,使用时传入图片和图片对应的数据,再创建实例。

import Carousel from './js/Carousel.js';
  var itemList1 = [{
                day: 26,
                date: "/Oct.2020",
                title: "秘境之蓝 无阿里不西藏 自驾阿里小北线",
                src: "./carousel_img/a.jpg",
            },
            {
                day: 25,
                date: "/Oct.2020",
                title: "这是一个什么样的国家?",
                src: "./carousel_img/b.jpg",
            },
            {
                day: 24,
                date: "/Oct.2020",
                title: "在徽州,给秋天写了8封信",
                src: "./carousel_img/c.jpg",
            },
            {
                day: 23,
                date: "/Oct.2020",
                title: "「穿过狂野的风」赶赴内蒙的追羊计划",
                src: "./carousel_img/d.jpg",
            },
            {
                day: 22,
                date: "/Oct.2020",
                title: "爱让我们无所不能|南极大冒险",
                src: "./carousel_img/e.jpg",
            },
        ];
        let carousel1 = new Carousel(itemList1);
        carousel1.appendTo(".div1");
        animation();
        function animation(){
            requestAnimationFrame(animation);
            carousel1.update();
            // carousel2.update();
}

代码:

import Component from './Component.js';
 
export default class Carousel extends Component{
    
    imgList;
    bnList;
    imgCon;
    dot;
    dotList=[];
    data;
    direction;
    pos=0;
    x=0;
    speedX=1;
    bool=false;
    time=200;
    autoBool=true;
 
    // WIDTH=13.66;
    // HEIGHT=4.55;
    WIDTH;
    HEIGHT;
    
    constructor(_data,_width,_height){
        super("div");
        this.data=_data;
        this.width = _width;
        this.height = _height;
        this.elem.className = "carousel";
        // Object.assign(this.elem.style,{
        //     width:this.WIDTH "rem",
        //     height:this.HEIGHT "rem",
        //     position:"relative",
        //     overflow:"hidden",
        // });
        let arr = ["./carousel_img/left.png","./carousel_img/right.png"];
        let _imgList = this.data.reduce((value,item)=>{
            if(item.src) value.push(item.src);
            return value
        },arr);
        this.loadImg(_imgList,this.createCarousel);
        // window.addEventListener("resize",e=>this.resizeHandler(e));
    }
 
    createCarousel(imgList){
 
        Object.assign(this.elem.style,{
            width:this.WIDTH "rem",
            height:this.HEIGHT "rem",
            position:"relative",
            overflow:"hidden",
        });
 
        this.imgList = imgList;
        this.bnList = this.imgList.splice(0,2);
 
        imgList.forEach(item=>{
            Object.assign(item.style,{
                width:this.WIDTH "rem",
                height:this.HEIGHT "rem",
            })
        })
 
        this.createimgCon();
        this.createDotList();
        this.createBn();
        // 动画一般在外面做,类里面只需要写状态更新即可。
        // this.animation();
 
        // 鼠标停留在轮播图上时不进行自动轮播。
        this.elem.addEventListener("mouseenter",e=>this.mouseHandler(e));
        this.elem.addEventListener("mouseleave",e=>this.mouseHandler(e));
    }
    createimgCon(){
        this.imgCon = document.createElement("div");
        Object.assign(this.imgCon.style,{
            width:this.WIDTH*2 "rem",
            height:this.HEIGHT "rem",
            position:"absolute",
        });
        let item = this.createItem(this.imgList[0],this.data[0]);
        this.imgCon.appendChild(item);
        this.elem.appendChild(this.imgCon);
    }
    createItem(img,obj){    
        let item = document.createElement("div");
        Object.assign(item.style,{
            width:this.WIDTH "rem",
            height:this.HEIGHT "rem",
            position:"relative",
            float:"left",
        });
        let title = document.createElement("div");
        Object.assign(title.style,{
            position:"absolute",
            left:"15%",
            top:"0.3rem",
            fontSize:"0.3rem",
            color:"#ffffff",
            textShadow:"0.02rem 0.02rem 0.02rem #000000",
            width:"8rem",
            lineHeight:"0.5rem",
        })
        let head1=document.createElement("div");
        Object.assign(head1.style,{
            height:"0.5rem",
        })
        head1.textContent = obj.date;
        let span = document.createElement("span");
        Object.assign(span.style,{
            fontSize:"0.4rem",
        });
        span.textContent = obj.day;
        let head2 = document.createElement("div");
        Object.assign(head2.style,{
            height:"0.5rem",
        })
        head2.textContent = obj.title;
        head1.insertBefore(span,head1.firstChild);
        title.appendChild(head1);
        title.appendChild(head2);
        item.appendChild(title);
        item.appendChild(img);
 
        return item;
    }
    createDotList(){
        this.dot = document.createElement("ul");
        Object.assign(this.dot.style,{
            listStyle:"none",
            margin:0,
            padding:0,
            position:"absolute",
            left:(this.WIDTH-1.8)/2 "rem",
            bottom:"0.3rem",            
        })
        for(let i=0;i<this.imgList.length;i  ){
            let li = document.createElement("li");
            Object.assign(li.style,{
                width:"0.18rem",
                height:"0.18rem",
                borderRadius:"0.2rem",
                marginLeft:i===0?"0px":"0.2rem",
                border:"0.02rem solid red",
                float:"left",
            })
            this.dot.appendChild(li);
            this.dotList.push(li);
        }
        this.dot.addEventListener("click",e=>this.dotClickHandler(e));
        this.elem.appendChild(this.dot);
    }
    createBn(){
        for(let i=0;i<this.bnList.length;i  ){
            Object.assign(this.bnList[i].style,{
                position:"absolute",
                top:(this.HEIGHT*100-this.bnList[i].height)/2/100 "rem",
            })
            if(i===0){
                this.bnList[i].style.left = "0.5rem";
            }else{
                this.bnList[i].style.right = "0.5rem";
            }
            this.bnList[i].addEventListener("click",e=>this.bnClickHandler(e));
            this.elem.appendChild(this.bnList[i]);
        }
    }
    bnClickHandler(e){
        if(this.bool) return
        if(e.target===this.bnList[0]){
            this.direction="left";
            this.pos  ;
            if(this.pos>this.imgList.length-1) this.pos = 0;
        }else{
            this.direction="right";
            this.pos--;
            if(this.pos<0) this.pos=this.imgList.length-1;
        }
        this.bool=true;
        this.createNextItem();
    }
    dotClickHandler(e){
        if(e.target.constructor!==HTMLLIElement) return    //这里因为是对父元素进行侦听,因此要先判断点击的是不是li,如果点击的不是小圆点就不能改变开关,直接return。不能先改变开关。
        if(this.bool)return
        for(let i=0;i<this.dotList.length;i  ){
            if(e.target===this.dotList[i]){
                if(this.pos===i) return
                this.direction=i<this.pos?"right":"left";
                this.pos=i;
            }
        }
        this.bool=true;
        this.createNextItem();
    }
    createNextItem(){
        let nextItem=this.createItem(this.imgList[this.pos],this.data[this.pos]);
        if(this.direction==="left"){
            this.imgCon.appendChild(nextItem);
            this.x=0;
        }else{
            this.imgCon.insertBefore(nextItem,this.imgCon.firstChild);
            this.x=-this.WIDTH;
        }
        this.imgCon.style.left=this.x "rem";
    }
    update(){
        this.imgMove();
        this.autoPlay();
    }
    // 这里只需要做一个状态更新即可。
    // 动画在外面做。
    // animation(){
    //     requestAnimationFrame(this.animation);
    //     if(!this.bool) return
    //     this.imgMove();
    // }
    imgMove(){
        if(!this.bool) return
        if(this.direction==="left"){
            this.x-=this.speedX;
            if(this.x<-this.WIDTH){
                this.imgCon.firstElementChild.remove();
                this.x=0;
                this.bool=false;
            }
        }else{
            this.x =this.speedX;
            if(this.x>0){
                this.imgCon.lastElementChild.remove();
                this.x=0;
                this.bool=false;
            }
        }
        this.imgCon.style.left=this.x "rem";
    }
    autoPlay(){
        if(!this.autoBool) return
        this.time--;    //增加防抖
        if(this.time===0){   
            let evt = new Event("click");
            this.bnList[0].dispatchEvent(evt);
            this.time=200;
        }
    }
    resizeHandler(e){
        document.documentElement.style.fontSize=document.documentElement.clientWidth/(this.WIDTH*100)*100 "px";
    }
    appendTo(parent){
        if(typeof parent==="string") parent = document.querySelector(parent);
        parent.appendChild(this.elem);
        if(!isNaN(this.WIDTH) && !isNaN(this.HEIGHT)) return
        if(parent===document.body){
            this.WIDTH = 13.66;
            this.HEIGHT = 4.55;
        }else{
            let rect = parent.getBoundingClientRect();
            this.WIDTH=rect.width/100;
            this.HEIGHT=rect.height/100;
        }
    }
    mouseHandler(e){
        if(e.type==="mouseenter"){
            this.autoBool=false;
        }else{
            this.autoBool=true;
        }
    }
 
    // 图片预加载
    loadImg(_imgList,_callBack){
        let img = new Image();
        img.i=0;
        img.arr=[];
        img.imgList=_imgList;
        // img.callBack=_callBack;
        img.src=_imgList[img.i];
        img.addEventListener("load",e=>this.imgLoadFinishHandler(e));
    }
    imgLoadFinishHandler(e){
        // console.log(e.currentTarget);
        e.currentTarget.arr.push(e.currentTarget.cloneNode());
        e.currentTarget.i  ;
        if(e.currentTarget.i<e.currentTarget.imgList.length){
            e.currentTarget.src = e.currentTarget.imgList[e.currentTarget.i];
        }else{
            // e.currentTarget.callBack(e.currentTarget.arr);
            this.createCarousel(e.currentTarget.arr);
        }
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持Devmax。

JS实现轮播图案例的更多相关文章

  1. html5 拖拽及用 js 实现拖拽功能的示例代码

    这篇文章主要介绍了html5 拖拽及用 js 实现拖拽,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  2. amaze ui 的使用详细教程

    这篇文章主要介绍了amaze ui 的使用详细教程,本文通过多种方法给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  3. swift皮筋弹动发射飞机ios源码

    这是一个款采用swift实现的皮筋弹动发射飞机游戏源码,游戏源码比较详细,大家可以研究学习一下吧。

  4. Swift与Js通过WebView交互

    开发环境:Swfit2.3XCode8.2基础概念jscontext,jscontext是代表JS的执行环境,通过-evaluateScript:方法就可以执行一JS代码JSValue,JSValue封装了JS与ObjC中的对应的类型,以及调用JS的API等JSExport,JSExport是一个协议,遵守此协议,就可以定义我们自己的协议,在协议中声明的API都会在JS中暴露出来,才能调用Swif

  5. JSCore swift

    如果双方相互引用,会造成循环引用,而导致内存泄露。以上是Jscore的基本使用,比较简单

  6. Swift WKWebView的js调用swift

    最近项目需求,需要用到JavaScriptCore和WebKit,但是网上的资源有限,而且比较杂,都是一个博客复制另外一个博客,都没有去实际敲代码验证,下面给大家分享一下我的学习过程。

  7. Swift WKWebView的swift调用js

    不多说,直接上代码:在html里面要添加的的代码,显示swift传过去的参数:这样就实现了swift给js传参数和调用!

  8. 在 Swift 專案中使用 Javascript:編寫一個將 Markdown 轉為 HTML 的編輯器

    你有強烈的好奇心,希望在你的iOS專案中使用JavaScript。jscontext中的所有值都是JSValue對象,JSValue類用於表示任意類型的JavaScript值。因此,我們既需要寫Swift代碼也要寫JavaScript代碼。此外,我們還會在JavaScript中按照這個類的定義來創建一個對象并對其屬性進行賦值。從Swift中呼叫JavaScript就如介紹中所言,JavaScriptCore中最主要的角色就是jscontext類。一個jscontext對象是位於JavaScript環境和本

  9. swift - WKWebView JS 交互

    本文介绍WKWebView怎么与js交互,至于怎么用WKWebView这里就不介绍了HTML代码APP调JS代码结果JS给APP传参数首先注册你需要监听的js方法名2.继承WKScriptMessageHandler并重写userContentController方法,在该方法里接收JS传来的参数3.结果

  10. swift 开发UIWebView跟JS的交互

    前言作为小白的我,才开始入门IOS,选择了swift来进行入门学习,学习做着公司一个简单的小小项目,该项目需要进行跟H5进行交互,然后我就开始研究了UIWebView的使用,其实基本原理跟Android的一样,因为我是Android开发的,所以就顺水推舟了。))//这里设置你需要加载的地址}overridefuncdidReceiveMemoryWarning(){super.didReceiveMemoryWarning()//disposeofanyresourcesthatcanberecreate

随机推荐

  1. js中‘!.’是什么意思

  2. Vue如何指定不编译的文件夹和favicon.ico

    这篇文章主要介绍了Vue如何指定不编译的文件夹和favicon.ico,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

  3. 基于JavaScript编写一个图片转PDF转换器

    本文为大家介绍了一个简单的 JavaScript 项目,可以将图片转换为 PDF 文件。你可以从本地选择任何一张图片,只需点击一下即可将其转换为 PDF 文件,感兴趣的可以动手尝试一下

  4. jquery点赞功能实现代码 点个赞吧!

    点赞功能很多地方都会出现,如何实现爱心点赞功能,这篇文章主要为大家详细介绍了jquery点赞功能实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  5. AngularJs上传前预览图片的实例代码

    使用AngularJs进行开发,在项目中,经常会遇到上传图片后,需在一旁预览图片内容,怎么实现这样的功能呢?今天小编给大家分享AugularJs上传前预览图片的实现代码,需要的朋友参考下吧

  6. JavaScript面向对象编程入门教程

    这篇文章主要介绍了JavaScript面向对象编程的相关概念,例如类、对象、属性、方法等面向对象的术语,并以实例讲解各种术语的使用,非常好的一篇面向对象入门教程,其它语言也可以参考哦

  7. jQuery中的通配符选择器使用总结

    通配符在控制input标签时相当好用,这里简单进行了jQuery中的通配符选择器使用总结,需要的朋友可以参考下

  8. javascript 动态调整图片尺寸实现代码

    在自己的网站上更新文章时一个比较常见的问题是:文章插图太宽,使整个网页都变形了。如果对每个插图都先进行缩放再插入的话,太麻烦了。

  9. jquery ajaxfileupload异步上传插件

    这篇文章主要为大家详细介绍了jquery ajaxfileupload异步上传插件,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  10. React学习之受控组件与数据共享实例分析

    这篇文章主要介绍了React学习之受控组件与数据共享,结合实例形式分析了React受控组件与组件间数据共享相关原理与使用技巧,需要的朋友可以参考下

返回
顶部