The native JS realizes the revolving Trojan horse type Picture Carousel plug-in _javascript skill

Source: Internet
Author: User
Tags time interval

I have written three pictures of the carousel, one is simple native JS implementation, there is no animation effect, a combination of jquery implementation, fade in and out of the switch. Now want to do a cool little on the blog or personal site, then you can show your work. Stroll the web, found that there is a merry-go-round of the jquery plug-in course, a bit cool, so want to use the original JS package out. Do it to find, not as easy as they think ... Not long-winded, explain the implementation process.

Second, the effect

Because its own server is not ready. Online demo not (Orz ...), can only put a picture of the effect.

From the picture can still see the approximate effect, I will not say more. To see the real code effect, welcome to my github above download code, don't forget to give my GitHub project to point a star Oh ^_^

Third, the implementation process

HTML structure

 <div class= "Carrousel-main" data-setting= ' {"width": 1000, "height": 400, " Carrouselwidth ": 750," carrouselheight ":" scale ": 0.9," verticalalign ":" Middle "} ' > <div class= ' Carrousel-btn carrousel-btn-pre "></div> <ul class=" carrousel-list "> <li class=" Carrousel-item " > <a href= "#" ></a> </li> <li class= "Carrousel-item" > & Lt;a href= "#" ></a> </li> <li class= "Carrousel-item" > <a href= "#" ></a> </li> <li class= "Carrousel-item" > <a href= "#" >< ; img src= "img/4.jpg" ></a> </li> <li class= "Carrousel-item" > <a href= "#" ></a> </ul> <div class=" carrousel-btn carrousel-btn-next "></div> </div>" /pre> 

This structure is the same as the general rotation of the HTML code structure, slightly different is that the main carousel Div has a data-setting attribute, this property is some of the parameters of the carousel effect. The specific meaning of the parameters will be explained later.

CSS part of the code is not pasted, the most important thing is to pay attention to the absolute positioning of elements, by the effect of the picture can be seen, the location of each image, the size is different, so these are through JS control, and therefore need absolute positioning. The following focus on the JS implementation process.

JS implementation process

Here are a few JS key steps, after doing these steps, there should be no difficulty.

① Default Parameters

Since it is the encapsulation plug-in, then there must be some parameters of the default value needs to be configured. In this plug-in, the main parameters are as follows:
width:1000,//width of the slide area
height:400,//The height of the slide area
carrouselwidth:700,//Slide the width of the first frame
carrouselheight:400,//The height of the first frame of the slide
scale:0.9,//records show proportional relationships, for example, the second picture is much higher than the first picture shows.
autoplay:true,//whether to play automatically
timespan:3000,//Automatic Playback time interval
VerticalAlign: ' Middle '//Picture alignment, there are top\middle\bottom three ways, the default is middle

② Package Objects

Because a Web site may have multiple places to use the same carousel plug-in, so encapsulation is critical. Once you have defined this object, if you define an initialization method for an object, you can create multiple objects by passing in the same dom of all the classes. So, my initialization method is as follows:

Carousel.init=function (carrousels) {
 var _this=this;
  Converts nodelist to an array of
  var cals= toArray (carrousels); <br>//  * Because native JS gets all the classes, obtains a nodelist, is a class If you want to use an array of methods, you need to convert to a real array. Here ToArray is the conversion method. *
  /Cals.foreach (function (item,index,array) {
  new _this (item);}
  );
 

In this way, when I window.onload, I invoke Carrousel.init (Document.queryselectorall ('. Carrousel-main ')) so that I can create multiple rotations!

③ Initialize the position parameter of the first frame

Because the parameters for all the frames after the first frame are defined by reference to the first frame, it is critical to define the first frame.

 Setvalue:function () {this.carrousel.style.width=this.
settings.width+ ' px '; This.carrousel.style.height=this.
 settings.height+ ' px '; /* Left and right button settings, where you want to let the button evenly divide the rotation area after the first frame width minus the area, z-index than the first frame of all the pictures are high, and the picture just right and left, so the value of the Z-index is half the number of pictures. * * var btnw= (this.
 Settings.width-this.settings.carrouselwidth)/2;
 this.prebtn.style.width=btnw+ ' px '; This.prebtn.style.height=this.
 settings.height+ ' px ';
 
 This.prebtn.style.zindex=math.ceil (THIS.CARROUSELITEMS.LENGTH/2);
 this.nextbtn.style.width=btnw+ ' px '; This.nextbtn.style.height=this.
 settings.height+ ' px ';
 This.nextbtn.style.zindex=math.ceil (THIS.CARROUSELITEMS.LENGTH/2);
 The first frame related setting this.carrouselfir.style.left=btnw+ ' px '; This.carrouselfir.style.top=this.setcarrouselalign (this.
 settings.carrouselheight) + ' px '; This.carrouselfir.style.width=this.
 settings.carrouselwidth+ ' px '; This.carrouselfir.style.height=this.
 settings.carrouselheight+ ' px ';
This.carrouselfir.style.zindex=math.floor (THIS.CARROUSELITEMS.LENGTH/2); },

Here, when the new object is, get the data-setting parameter to the DOM node and update the default parameter configuration. Here's a place to be aware that parameters that get the DOM cannot be updated directly by assigning the default parameters, because when a user configures a parameter, all parameters are not necessarily configured once. If you assign a value directly and the user does not have all of the parameters configured, it can cause parameter loss. Here I wrote an object extension method similar to the $.extend method in jquery to update the parameters. The specific is not listed, interested can go to download.

④ Other picture location settings

The picture here is actually a picture except the first one, evenly divided into the left and right two, while the left side of the picture position and the right-hand side is different, and therefore need to be configured separately:

Set the position relationship of the right picture
var rightindex=level;
Rightslice.foreach (function (item,index,array) {
 rightindex--;
 var I=index;
 The picture on the right side of the rw=rw*carrouselself.settings.scale;//is a rh=rh*carrouselself.settings.scale that is gradually smaller according to the scale ratio
 ;
 
 item.style.zindex=rightindex;//to the right z-index the smaller the value, you can use the picture number of the general gradual decline
 item.style.width=rw+ ' px ';
 item.style.height=rh+ ' px ';
 ITEM.STYLE.OPACITY=1/(++i); The greater the transparency of the right <br>    //The Gap calculation method here is: The Carousel area minus the first frame width, except 2, and then the left or right picture count
 Item.style.left= (constoffset+ (++index) *gap-rw) + ' px ';//left's value is actually the first frame left+ the width of the first frame minus the width of the item
 Item.style.top=carrouselself.setcarrouselalign (RH) + ' px ';
};

The settings on the left are similar and simpler, and are not discussed in detail.

Adjust the position size of all pictures when ⑤ rotation

This step is critical, click on the right button to the next one is left rotation, and click on the left button on the right rotation. At this point, we just need to take all the pictures as a ring, click once, change the position that completes the rotation. In the case of the left rotation, the second argument is equal to the first one, and the third is the second one ... And the last one is equal to the first one. When the right rotation, so that the first argument is equal to the second, the second parameter is equal to the third ... And the last one is equal to the first one.

Here, let's talk about left rotation.

if (dir== ' left ') {ToArray (this.carrouselitems). ForEach (function (Item,index,array) {var pre; if (index==0) {//To determine whether the first pre=_this.carrousellat;//makes the first pre equal to the last one var width=pre.offsetwidth;//get the corresponding parameter var height=pr
   E.offsetheight;
   var Zindex=pre.style.zindex;
   var opa=pre.style.opacity;
   var top=pre.style.top;
  var left=pre.style.left;
   }else{var width = tempwidth;
   var height = tempheight;
   var zindex = Tempzindex;
   var opa = tempopacity;
   var top = Temptop;
  var left = Templeft;
  //Here needs attention, because the second picture is to refer to the first one, and this change, the first one is changed first, so must first of the relevant parameters of the first to be saved temporarily.
  Tempwidth = Item.offsetwidth;
  Tempheight = Item.offsetheight;
  Tempzindex = Item.style.zIndex;
  tempopacity = item.style.opacity;
  Temptop = Item.style.top;
 
  Templeft = Item.style.left;
  item.style.width=width+ ' px ';
  item.style.height=height+ ' px ';
  Item.style.zindex=zindex;
  Item.style.opacity=opa;
   Item.style.top=top;
   Item.style.left=left; Animate (item, ' Left ', left,function () {//custom native Js animation function _this.rotateflag=true;
  });
}); }

The rotation here, if not using some animation excessive, will appear very blunt. But the native JS does not have the animation function, here I wrote a imitate animation function. The principle is to get the original style value of the DOM, compared to the new incoming value. Define a speed in some ways. My speed here is to use the difference in addition to 18. Then define a timer, refer to the jquery source inside the time interval for every 13 milliseconds to perform. Then the original style value after each plus speed equal to the value of the passing time to clear the timer can be. It can be seen here.

All right, the key points are pretty much the same, and it's going to be easy if you understand these processes!

Iv. summarizing and thinking

Summarize:

Personal feeling this is still a better understanding of plug-ins. It would be quite easy if you could combine jquery. But with original writing, there is still some less fluid feeling. It should be a custom animation that is not as good as the jquery encapsulated animation bar.

Also, this plugin because the picture needs to be evenly divided between the left and right sides, so for even number of pictures, the method here is to clone the first one, then add to the end, forming an odd.

Thinking:

If there is a bug, it is that I have defined a Rotateflag flag to determine whether the current can be rotated, is to prevent a quick click on the time to keep up. I press the Rotateflag set to False, and then after the end of the animation to set the Rotateflag to true, but it seems that the role is not obvious, I hope that the great God can teach, we common progress.

The above is the entire content of this article, more information please refer to: JavaScript picture Carousel Effect Summary, thank you for reading.

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.