Worth sharing JavaScript implementation Picture Carousel component _javascript Skills

Source: Internet
Author: User
Tags prev

The example of this article for everyone to share the JavaScript implementation of the image of the use of carousel components for your reference, the specific content as follows

Effect:

Automatically loop the picture, there is a button below to switch to the corresponding picture.
Add an animation to make the picture switch.
The mouse stops in the picture, the carousel stops, appears about two arrows, clicks may switch the picture.
When the mouse moves away from the picture area, the carousel continues from its current position.
Provides an interface to set the direction of the carousel, whether to cycle, interval time.
Click to view Demo

Requirements for HTML, CSS:

<div class= "Carousel-box" >
 <div class= "Carousel" >
  <ul class= "Clearfix" >
   <li> </li> <li> </li>
   <li></li>
   <li></li>
   <li></li>
   <li></li>
  </ul>
 </div>
</ Div>

* Must be two box nesting, the innermost box needs to have a UL, the picture needs to be included in Li.
* You can change the class name and replace the corresponding class name in the CSS file. The correct DOM element is passed in when the component is configured.
* Do not limit the width and number of pictures, you can change the values in the CSS file.

/* The value that needs to be changed
/* Carousel img{ 
 width:600px;
 height:400px
}
. Carousel,
. carousel-box {
 width:600px;/* Single Picture Width * * *
 height:400px/* Single Picture Height * *
Carousel ul{
 width:3600px/* Single picture width x Picture quantity * *

Principle:

Arrange all the pictures horizontally, the outermost container and the package container to set the Overflow:hidden. The outermost container is used for positioning buttons and arrows. Use the ScrollLeft property of the package container to control which picture is displayed.

Ideas:

To implement these features, there are some ways to do this:

1. Picture switching function. Takes a parameter that indicates the direction of scrolling. Call the easing function to toggle the picture. Call the toggle button icon function to light the corresponding button.

2. Easing function.

3. Lighting the button function.

4. Initialize the function. Used to bind events, create buttons and arrows, initialize the original position.

5. Create an arrow function.

6. Create a button function.

7. Start the Carousel function.

8. Carousel function.

9. Stop function. Used to stop the carousel.

There are some common methods :

$ (): select Dom element.

addclass (ele, "ClassName"): Adds a class name to an element.

removeclass (ele, "ClassName"): removes the class name of the element.

$.add (ele, "type", fun): binds an event to a DOM node.

getcss (ele, "prop"): Gets the value of the corresponding property of the element.

$.delegatetag ("selector", "TagName", "type", fun): event agent.

Realize:

Suppose there are 6 pictures, each picture has a width of 600px. Complete according to functional independence:

1. Easing function liner
The function of the easing function is to change the attribute value of the target element at 1.1 points until the target value is reached. The element that uses it may be a horizontal carousel picture, or a picture of a vertical carousel, or a small box that wants to get from the page left to the right side of the page. So it should receive four parameters (the target element, the property value to be changed, the target value, the number of moves).

Liner=function (ele,prop,next,num) {
 var speed= (next-ele[prop))/num,
  i=0;
 (function () {
  ele[prop]+=speed;
  i++;
  if (i<num) {
   settimeout (arguments.callee,30);
  }
 }) (); 
},

2. Lighting button Function Light
The Highlight button is essentially adding an active class to the button, and the off button removes the active class from the button.

So how do you know which one is the current button?

The easiest way is to get it directly, so you can add a index property to each button, and when you need to light the button, the index of the button that will be lit is passed to the function.

So how do you know which button is going to be extinguished?

The easiest way is to get it directly, so you can add a variable active at the end of the scope chain, remember the button that is currently on, and this function will just turn him off.

Light=function (index) {
 removeclass (active, "active");
 active=$ (this.wrapselec+ "" + "[index=" +index+ "]");
 AddClass (Active, "active");
}

3. Picture switching function Go
you need to calculate the next ScrollLeft value:

If you move to the left, ScrollLeft should-600, if it's already 0, switch to 3000. So it is ele.scrollleft===0?width* (len-1): ele.scrollleft-width;

If it is moving to the right, scrollleft should be +600, or 0-->600,600-->1200,...,3000-->0. Here you can use judgment as above, or you can use a formula next= (cur+distance)% (distance*num). i.e. (ele.scrollleft+width)% (Width*len)

You need to get the index of the Next button to be lit:

Like the idea of calculating scrollleft, move left: Index===0? Len-1:index-1; Move to right: (index+1)%len

Go=function (dire) {
 var index=active.getattribute ("index")-0,
  Nextindex,
  nextposition;
 if (dire=== "next") {
  nextindex= (index+1)%len;
  nextposition= (ele.scrollleft+width)% (Width*len);
 } else{
  nextindex=index===0 len-1:index-1,
  Nextposition=ele.scrollleft===0?width*len: ele.scrollleft-width;
 }
 Light (nextindex);
 Animate.liner (Ele, "ScrollLeft", nextposition); 
}

The Len (total picture), Width (picture width), ele (Package container) are also accessed by other functions, so they are also added to the end of the scope chain.

Len=ele.getelementsbytagname ("img"). Length

Width=parseint (Getcss (Ele.getelementsbytagname ("img") [0], "width ");

ele=$ (Eleselec), Eleselec is the selector of the parcel container, such as. Carousel

4. Create arrow function Createarrow
creates a left arrow that binds the event handler function to move left. Creates an arrow to the right and binds the event handler function to move to the right.

Createarrow=function () {
 var prev=document.createelement ("div"),
  next=document.createelement ("div");
 Prev.appendchild (document.createTextNode ("<"));
 Next.appendchild (document.createTextNode (">"));
 Prev.classname= "Arrow prev";
 Next.classname= "arrow next"; 
 Container.appendchild (prev);
 Container.appendchild (next);
 AddClass (Container, "hide");
 $.add (Next, "click", Function () {Go
  ("Next");
 });
 $.add (prev, "click", Function () {Go
  ("prev");}
 );

Container represents the outermost container and is also accessed by other functions, so it is also added to the end of the scope chain.

container=$ (Wrapselec), Wrapselec is the selector of the outermost container, such as. carousel-box

5. Create a button function createbtn
Add a index for each button to light and go off, add a class name to the group of buttons to set the style and get it:

Createbtn=function () {
 var div=document.createelement ("div"),
  btns= ';
 for (Var i=0;i<len;i++) {
  btns+= ' <a href= ' # ' index= ' ' +i+ ' ' ></a> ';
 }
 Div.innerhtml=btns;
 AddClass (Div, "carousel-btn");
 Container.appendchild (div);
}

6. Carousel function
to determine whether to call Go ("prev") or going ("next"), as required (clockwise, counterclockwise).

If a loop is required, call yourself again. If it is not cycled, it stops after a round robin.

So here we need a variable to determine the direction, a variable to determine whether the loop, a variable to count.

So another four variables are added to the end of the scope chain. direction, loop, count, begin is used to clear the timer.

Circle=function () {
 count++;
 if (loop| | Count<len) {
  if (direction=== "forward") {go
   ("Next");
  } else{go
   ("prev");
  }
 Begin=settimeout (arguments.callee,t);
}

7. Stop function stops

Stop=function () {
 cleartimeout (begin);
}

8. Initialization function init
If you are using the carousel for the first time, create the buttons and arrows, bind the button click event handler (get the clicked index of Click to light it, switch to the corresponding picture), and then display the corresponding picture and button according to the clockwise or counterclockwise.

So here again a variable is added to the end of the scope chain to indicate whether it has been initialized.

Init=function () {
 createbtn ();
 Createarrow ();
 $.delegatetag (wrapselec+ "" + ". Carousel-btn", "A", "click", Function (e,target) {
  $.prevent (e);
  Light (Target.getattribute ("index"));
  Animate.liner (Ele, "ScrollLeft", Target.getattribute ("index") *width);
 $.add (Container, "MouseEnter", function () {
  stop ();
  Removeclass (Container, "hide");
 };
 $.add (Container, "MouseLeave", function () {
  addclass (container, "hide");
  Begin=settimeout (circle,t); 
 }); if (direction=== "forward") {
  light (0);
 } else{
  Light (len-1);
  ele.scrollleft=width* (len-1);
 }
 havestart=true;
}

9. Start the round-seeding function start

This function is used as an interface to control the rotation direction, interval time, and whether or not to cycle. The counter is zeroed.

Because it is possible to start the carousel repeatedly, you need to clear the timer before each start.

Start=function (Dir,th,lo) {
 stop ();
 count=0;
 Direction=dir;
 t=th*1000;
 Loop=lo;
 if (!havestart) {
  init ();
 }
 Begin=settimeout (circle,t);
}

To here, all the functions that need to be used are already written, and if you throw these functions and the variables you need into a function, pass the class name or ID of the outer container container to it, the function returns an object that contains the start and stop methods, and the component is ready to use.

But there is a problem, this function is only one, that is, a page can only have one carousel instance. So, if you want a page that has two instances of a carousel using this component, you can't throw them into a function. Then you can only put it in the object. Each object has its own variables, and they share a set of methods.

Then, these variables are not directly accessible and need to be accessed through the object's properties, that is, this.

This is where the problem occurs, and this is the environment that will point to it, so when those variables are accessed in the event handler or in the timer, you cannot use this, but instead create a closure.

That is, when you can get this, you assign this to a variable, and then access the variable in the event handler or timer, and you get the correct object.

Use the Init function as an example to modify:

Carouselproto.init=function () {
 var that=this;
 THIS.CREATEBTN ();
 This.createarrow ();
 $.delegatetag (this.wrapselec+ "" + ". Carousel-btn", "A", "click", Function (e,target) {
  $.prevent (e);
  That.light (Target.getattribute ("index"));
  Animate.liner (That.ele, "ScrollLeft", Target.getattribute ("index") *that.width);
 $.add (This.container, "MouseEnter", function () {
  that.stop ();
  Removeclass (That.container, "hide");
 };
 $.add (This.container, "MouseLeave", function () {
  addclass (That.container, "hide");
  That.begin=settimeout (function () {
   that.circle ();
  },that.t); 
 }); if (this.direction=== "forward") {
  this.light (0);
 } else{
  this.light (this.len-1);
  this.ele.scrollleft=this.width* (this.len-1);
 }
 this.havestart=true;
};

After this is done, you can create an instance where each instance has its own attributes to record the state, and they all share the methods in the prototype.

If you are using prototype inheritance, you can create an object as the prototype object for the instance, and then create a function to produce the instance:

var carouselproto={};

Put the above methods to the object
carouselproto.light=
...
carouselproto.go= ...

carouselproto.stop= ... Create instance object function
var carousel=function (Eleselec,wrapselec) {
 var that=object.create (Carouselproto);
 That.wrapselec=wrapselec;
 that.ele=$ (Eleselec);
 that.container=$ (Wrapselec);
 That.len=that.ele.getelementsbytagname ("img"). Length;
 That.width=parseint (Getcss (That.ele.getElementsByTagName ("img") [0], "width"));
 return that;
}

Create an instance, using the component
var Carousel1=carousel (". Carousel", ". Carousel-box");
  Carousel1.start ("Forward", 3,true);
var Carousel2=carousel (". Carousel2", ". Carousel-box2");
  Carousel2.start ("Backward", 2,true);

Performance optimization:

1. When the clicked button is the button that is currently lit, the light and Animate.liner are still called once. So you can add a judgment statement, and if you click on the button just right, do not do the following.

$.delegatetag (this.wrapselec+ "" + ". Carousel-btn", "A", "click", Function (e,target) {
 $.prevent (e);
 var index=target.getattribute ("index");
 if (Index===that.active.getattribute ("index")) {
  return
 }
 that.light (index);
 Animate.liner (That.ele, "ScrollLeft", Target.getattribute ("index") *that.width);

2. When the picture is switched, the easing animation is being performed. If you click on the button or the arrow when the motion is not finished, you will get into the next animation, and then there will be confusion and picture dislocation. Performance can also be affected. To prevent this from happening, you can use a variable to record whether the easing animation is executing or not, click the button or arrow to execute the function.

Liner=function (ele,prop,next) {
 var speed= (next-ele[prop))/10,
  i=0;
 Ele.animating=true;
 (function () {
  ele[prop]+=speed;
  i++;
  if (i<10) {
   settimeout (arguments.callee,60);
  } else{
   ele.animating=false
  }
 }) (); 
}
if (!this.ele.animating) {
 this.light (nextindex);
  Animate.liner (This.ele, "ScrollLeft", nextposition);
}

Click to view Source

Reference resources:

MU-Class network-focus map Carousel Effect
"Javascript:the Good Parts"

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.