Native JavaScript for Seamless carousel mapping

Source: Internet
Author: User

Seamless Carousel is one of the most commonly used special effects, but in the actual development process, most of the developers will use the plug-in to the development of the carousel, then the bottom of how it is implemented, this article will focus on this issue.

Before discussing how to use native JS to seamlessly switch the animation of the carousel between pictures, let's talk about the CSS layout of the seamless carousel image.

First we need a div container to display the picture, and then put a line that we want to carousel into a div container with no gaps, and set Overflow:hidden to the DIV container so that you can see only one picture on the page. Then by using JS to move the UL left value can achieve the seamless rotation of the animation effect.

However, this is not enough, we also need to put the last picture in front of the first picture, as well as the last picture after the first picture, so that the purpose is to achieve the first picture and the last picture of the transition to achieve a seamless animation effect. The core code and layout effects are as follows:

<div id="Box"> <ul> <li>"img/5.jpg"></li> <li>"img/1.jpg"></li> <li>"img/2.jpg"></li> <li>"img/3.jpg"></li> <li>"img/4.jpg"></li> <li>"img/5.jpg"></li> <li>"img/1.jpg"></li> </ul></div>

is to set the Overflow:hidden effect before the div container:

After the layout is done, the next step is to use native JS for seamless carousel.

First of all we need two core functions, one for the image seamless switching of the deceleration movement, the other to get the left value of UL (note: Seamless carousel Every move is the entire UL left value)

function Fnmove (ele, obj,callback) {//parameter one: elements that require a dynamically changing style//parameter two: An object whose key is the CSS property name that needs to be changed, the value is the CSS property target value example {FONTSIZE:500,HEIGHT:140,OPACITY:50}//parameter three: callback if the animation ends calling the functionclearinterval (Ele.timer); //Create a timer dynamically modifies the CSS property value of the target element//storing a timer with Ele does not allow the timer number to be released, which prevents the timer from being blockedEle.timer =setinterval (function () {varFnstop =true;//mark to determine if all animations have reached the target value         for(varattrinchobj) {//Traversal object gets all the property names and target values that need to be modified            varCurr =0; //element Current CSS property value if property is opacity 0-1//because our speed is greater than or equal to 1 direct Operation 0-1 Decimal is not very good operation//we'll zoom in on him 100 times times .            if(attr = ='Opacity') {Curr= parseint (GetStyle (Ele, attr) * -)            }Else{Curr=parseint (GetStyle (Ele, attr))}//define a speed to increase the target element by 5 pixels every 30 milliseconds until the target value stop timer is reached (end of animation)//Deceleration motion target value (unchanged)-minus the current value (getting closer to the target) minus the result is getting smaller divided by 6 don't let the current value reach the target in a moment            varSpeed = (obj[attr]-Curr)/6; //Zoom Action 0.3 = 1-0.3 = 1 Avoid letting speed equal 0Speed = speed >0?Math.ceil (Speed): Math.floor (speed); if(Speed! =0) {Fnstop=false; }            //Console.log (Curr); //dynamically changing CSS property values if it's transparency, we're going to multiply it by 100 times times here. You need to restore the number back to 0-1.            if(attr = ='Opacity') {ele.style[attr]= Parsefloat ((curr + speed)/ -); //Transparency compatible write Pharaoh version browser transparency to 0-100Ele.style.filter ='Alpha (opacity:'+ (Curr + speed) +')'            }Else{ele.style[attr]= Curr + speed +'px'            }        }        //All animations complete, call the callback function (optional)        if(fnstop) {clearinterval (Ele.timer); if(callback) {callback (); }        }    },  -)

function GetStyle (ele, sattr) {//parameter one: The element object to get//parameter two: The style attributes to get//compatible notation Gets the value of the element CSS style//High-version browser getComputedStyle (element, Pseudo-Class), not pseudo-class set to NULL, returns a CSS style declaration object    if(window.getComputedStyle) {sattr= window.getComputedStyle (Ele,NULL) [sattr]; } Else {        //Low Version BrowserSattr =Ele.currentstyle (sattr); }    returnsattr}

With these two methods, it is easy to achieve seamless carousel.

First we need a timer to make the picture carousel every two seconds. Second, we also need a function to move the picture, put the function into the timer, call every two seconds, to achieve the carousel effect.

// Get the width of the image/li by JS, and get how many pixels each carousel moves var imgwidth = lilist[0// defines the subscript of the current carousel (used to record the next time the display of the first few pictures)var// the picture starts with the first one index==0 is actually the last picture // The subscript of the page dot highlight var num = 0// start of carousel Box.timer = SetInterval (Showright, 2000);
functionshowright () {index++; Num++; if(Num >=spans.length) { //spans is the same as the number of decimal points in the display picture num= 0; }    if(Index >= lilist.length) {//The first one (Li's last one) has been shown, and the second one     //set CSS properties directly left is no animation effect seamless let the last one jump back to the 1th oneUl.style.left =-imgwidth + ' px '; //Change the index value animation effect to move the first one to the secondindex = 2; } fnmove (UL, {left:-imgwidth *Index})  Activespan (num); //Light the small dots corresponding to the picture }
// Highlight Small dot method function Activespan (num) {     for (var i = 0; i < spans.length; i++) {    = "; 
    }    = ' bgcolor '}

next to the left and right button to bind the fixed-point event, and then every click of the button is called once Showright () function, with the showright () function, Showleft () The function is also easy to write ( note: Each click needs to clear the original rotation timer ):

function (e) {     // block event bubbling compatibility      e = e | | window.event;       true : E.stoppropagation ();      Clearinterval (Box.timer);      Showleft ();      }
function (e) { = e | | window.event; true : E.stoppropagation (); Clearinterval (Box.timer); Showright (); }

(The mouse is actually clicked on the left and right buttons ):

Finally, we use the For loop to tie the fixed-point event to each small dot, which involves JS one feature: Asynchronous event queue.

Here is a simple explanation: page loading is from the top down to the code to load synchronously, when the need for event-triggered callback function, JS will throw the callback function into the asynchronous event queue, and then continue to load the code. When an event in the page is triggered, JS invokes all of the callback functions bound to the event from the asynchronous event queue.

So, when we use a for loop to tie a point-and-click event to each small dot, we need to record the subscript for each small dot and read the subscript corresponding to the small dot in the callback function that calls the DOT event binding.

//add a click to a small dotfunctionSpansclick () { for(vari = 0; i < spans.length; i++) {        //record the subscript for each small dotspans[i].index=i; Spans[i].onclick=function(e) {e= e | |window.event; Window.event? E.cancelbubble =true: E.stoppropagation (); //reads the subscript of each small dotnum = This. Index; Index= num + 1;            //index is always 1 activespan (num) larger than Num ; Fnmove (UL, {left:-imgwidth *Index}) }    }}

(You actually have the mouse to click on the small dots)

Native JavaScript for Seamless carousel mapping

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.