Native JS object-oriented implementation simple carousel

Source: Internet
Author: User
Tags setinterval

Usually I used jquery to write the results of the carousel, the implementation process is not difficult, but also very convenient, in order to deepen the JS object-oriented understanding, I intend to use object-oriented implementation of a simple carousel, where the use of the literal way to achieve. To implement this process, we're going to encapsulate a motion function animate, where I'm using the uniform motion approach, which may experience not very well, after parsing the JS code I explained in detail. Don't say much nonsense, first on the code. Page layouts can be used according to their own habits.

HTML code:

CSS code:

*{    padding:0;    margin:0;    List-style-type:none;    Text-decoration:none;}. clear{    Clear:both;} a:hover{    Text-decoration:none;}. slide{    position:relative;    width:500px;    height:300px;    margin:20px Auto;    Overflow:hidden;}. Slide. img-box{    width:10000px;    Position:absolute;    left:0;    top:0;}. Slide. Img-box li{    float:left;    width:500px;    height:300px;}. Slide. Img-box Li img{    width:100%;    height:100%;}. icon{    Position:absolute;    right:8%;    bottom:6%;}. Icon span{    display:block;    Float:left;    width:15px;    height:15px;    border-radius:50%;    Background:white;    opacity:0.7;    margin-left:5px;}. icon. on{    Background:orange;    opacity:0.7;}

JS Code:

Window.onload = function () {function animate (ele, Xtarget, time) {var xPos = Ele.offsetleft,//Perform one motion at a time to get ele            The distance the element is offset from the left edge of the parent container.  Speed = 25;            Uniform motion Velocity if (math.abs (xtarget-xpos) <= speed) {//To be corrected when approaching the target position, since the distance traveled is not necessarily the integer multiple of the speed, which terminates the execution of animate after correction.            XPos = Xtarget;            Ele.style.left = XPos + ' px ';        return false; } XPos = XPos > Xtarget? Xpos-speed:xpos + speed;        The rotation direction left or right when processing if (ele.movement) {//guarantee that only one timer runs Cleartimeout (ele.movement) at a time;        } ele.style.left = XPos + ' px ';            Ele.movement = SetTimeout (function () {//) executes the animate function recursively until Math.Abs (Xtarget-xpos) <=speed is satisfied with the program termination condition.        Animate (Ele, Xtarget, time);    },time);        } function Moveindex (spanlist,index) {//According to the index let the corresponding index in the lower right plus the name on the class, to achieve highlighting.        for (var i = 0,len = Spanlist.length;i < len;i++) {spanlist[i].classname = ';    } spanlist[index].classname = ' on '; } functiOn AutoPlay (obj) {//Auto-carousel function if (++obj.index >= obj.aSpan.length) {obj.index = 0;        } moveindex (Obj.aspan,obj.index);    Animate (Obj.oul,-obj.index * 500,10);        } var slide = {//The implementation of the Carousel method is encapsulated in the slide object.            Init:function () {///Initialize Method This.oul = Document.queryselector ('. Img-box ');            This.aspan = Document.queryselectorall ('. icon span ');  This.index = 0;//defines a total index for the carousel This.timer = null;            Page load Auto-carousel Timer}, Play:function () {//By selecting a small icon in the lower right corner to display the corresponding index of the picture.            var = this; for (var i = 0;i < this.aspan.length;i++) {(function (j) {that.aspan[j].onmouseover = f                        Unction () {that.index = J;                        Moveindex (That.aspan,that.index);                    Animate (That.oul,-that.index * 500,10); }}) (i)}}, Autoslide:function () {///page started auto-carousel var that =This            This.timer = setinterval (function () {autoPlay (that);            },3000);            }, Hover:function () {///The method is primarily designed to implement an arrow placed in the Carousel area to stop automatic carousel, moving the function of continuing automatic carousel.            var = this;            var oslide = Document.queryselector ('. Slide ');            Oslide.onmouseover = function () {clearinterval (That.timer); } oslide.onmouseout = function () {That.timer = SetInterval (function () {AutoPlay (            That);              },3000);    }}}//The function on the object is called by Slide.init ();    Slide.play ();    Slide.autoslide (); Slide.hover ();}

1.animat function

The function has three parameters:

Ele: To move the target element, I am here to ul.

Xtarget: The target position, which is the target location to which the ele is to be moved.

Time: Refers to the interval of the timer in the Animate function, where I use 20ms.

The animate function uses recursion, each time the animate function is executed, the ele will move the speed distance relative to the original position, speed I given above is 25, so the whole movement is a uniform motion process, but this will have a bad experience, is the current position and target location distance is too large, the entire sliding process takes a long time, because the constant speed, the longer the distance is more time, so here is an algorithm,

Speed =math.ceil (Math.Abs (xtarget-xpos)/10), this is the gradual decline in velocity, from fast to slow, the longer the distance, the faster the front slide, the experience will be better, here I do not give a specific wording.

2.moveIndex function

This function should be well understood, which is to change the element class name of the corresponding index according to the input index parameter.

3.var = This

The purpose of this is actually to use that variable to hold the object of the function in the calling object itself, because in the subsequent processing, the object slide properties and methods may be used, and in the event handlers and timer handlers, the point of this is changed, So take the lead to save the object with that variable so that it can be used when needed.

This basically implements a simple object-oriented carousel effect.

Native JS object-oriented implementation simple carousel

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.