The implementation method of jquery carousel with a complete example _jquery

Source: Internet
Author: User
Tags extend prev setinterval

This example for you to share the jquery Carousel implementation code for your reference, the specific contents are as follows

1. Flashing mode of the carousel
Not discussed, the implementation is relatively simple, the effect is also better

2. Sliding Wheel Seeding
take the following HTML code as an example (slide to the left)

<div class= "Example" style= "Overflow:hidden; width:266px; " > 
 <ul style= "width:798px; float:left; height:216px; margin-left:0px;" >
 <li style= "width:266px; float:left; height:216px;" ></li>
 <li style= "width:266px; float:left; height:216px;" ></li>
 <li style= "width:266px; float:left; height:216px;" ></li>
 </ul>
</div> 

Plug-in Source: To achieve the left and up the carousel, manual switch is also left and up switch (manual switch key source)

var all = $panel. Find (' >li '),
 prevall = new Array ();
Prevall[0] = all.eq (0);
Save all nodes in front of the target node into Prevall, then add them sequentially to the back of the container for
(var i = 1; i < Len; i++) {
 all.eq (i). CSS ({display: ' None '});
 Prevall[i] = All.eq (i);
}
...

$panel. Animate ({' marginleft ':-options.width + ' px '}, options.duration, function () {for
 (var i = 0; i < Prevall.) Length i++) {
 $panel. Append ($ (prevall[i)). CSS ({display: ' block '});//////load all nodes before the current presentation node to the last
 }
 $panel. css ({ marginleft:0});



There are two main ways to realize sliding carousel
1 Toggle the parent element Margin-left, adding the first child element to the end of the parent container continuously
Simple Implementation

var $panel = $ (' example ');
var Scrolltimer = setinterval (function () {
  scrollnews ($panel);
 }, 3000);
function $scrollNews () {
 $panel. Animate ({' marginleft ': ' -266px '}, +, function () {
 $panel. css ({marginleft:0 ). Find (' >li:first '). Appendto ($panel);
 })
}

One problem with this approach is that there may be compatibility issues on old ie.

2) Cumulative way to set the parent element margin-left
However, when the Margin-left is set to the minimum (slide to the last element), the position of the first child element is set to the back of the last child element, and when the last element is scrolled to the first element, The parent element is margin-left to 0 and the first child element is placed in place. Give me a simple code example

var $panel = $ ('. Example '),
 index = 0;
var Scrolltimer = setinterval (function () {
  scrollnews ($panel);
 }, 3000);

function Scrollnews () {
 if (++index >= 2) {
 $panel. css ({
 ' paddingleft ': 266 + ' px '
 })
 $ Panel.find (' >li:first '). css ({
 ' position ': ' absolute ', ' left 
 ': 266*index + ' px '
 });
 $panel. Animate ({' marginleft ': -266*index + ' px '}, function () {
 if (++index > 3) {
 $panel. css ({Marginle ft:0});
 if (index >= 3) {
 index = 0;
 $panel. css ({ 
 marginleft:0,
 ' paddingleft ': 0 
 });
 $panel. Find (' >li:first '). css ({
 ' position ': ' Static ', ' left 
  ': ' Auto '
 })
}}

More complex scrolling plug-ins need to support horizontal and vertical scrolling (four directions), you can manually toggle the focus, you can flip the next one. Enclosed I write the complete plug-in source code
Plugin source code jquery.nfdscroll.js: Support Horizontal and vertical direction (four direction) scrolling, manual switch will scroll with the direction of the switch

/** * @author ' Chen Hua ' * @date ' 2016-5-10 ' * @description sliding carousel Plug-in supports horizontal and vertical sliding carousel * @example HTML: <div class= "Nfdn ews_topnews Example "> <!--scrolling content ul--> <ul> <li><a href=" xxx "target=" _blank "title=" xxx ">&l t;/a></li> <li><a href= "xxx" target= "_blank" title= "xxx" ></a></li> <li><a href= "xxx" target= "_blank" title= "xxx" ></a></li> <li><a href= "xxx" target= "_blank" title= " xxx "></a></li> </ul> <!--focus list, optional--> <ol> <li class=" "></li> <l I class= "" ></li> <li class= "" ></li> <li class= "" ></li> </ol> <!--prev and Next, Optional--> <div> <a class= "Nfdscroll-prev" href= "javascript:void (0);" ></a> <a class= "Nfdscroll-next" href= "javascript:void (0);" ></a> </div> </div> JS: $ ('. Example '). Nfdscroll ({startindex:0, Width: ' 266 ', Height: ' 216 ', I Nterval:2000, selected: ' Circle ', Prevtext: ', Nexttext: ', deriction: ' Left ', callback:function (index, $currentNode) {
 Console.log (Index)}}); * @param startIndex {number} is scrolled by default from the first few scrolls, optionally (0-n,0 is the initial, default is 0) * @param width {number} scroll volume, optional (when width is 0 to indicate no width) * @param Height {Number} scroll level, optional (indicates no height when height is 0) * @param interval {number} interval, per millisecond, negative value indicates no automatic scrolling * @param duration {Number} Animation Duration * @param selected {string} Scroll Toggle Small icon (Focus list) Current class * @param deriction {string} scrolling direction, support for Left/right and Top/bottom * @para M callback {Function} The callback that triggers when the slide animation ends, parameters (index, $currentNode), index: The indexes of the nodes that are displayed after the carousel; CurrentNode: jquery object for the node currently displayed after the end of the carousel * param prevtext {string} The text of the previous button, which defaults to the text of the Next button on the "previous" * @param nexttext {string}, by default to "next" */JQuery.fn.extend ({nfdscroll: function (options) {var defaultopt = {startindex:0, width:0,//scroll width, optional (indicates no width when width is 0) height:0,//the height of the scroll body, optionally (when the height is 0) Do not set height) interval:1000,//interval milliseconds duration:400,//animation duration selected: ' Selected ',//scroll Toggle Small icon Current class Prevtext: ' prev ', Nexttext: ' UnderA ', deriction: ' Left ',//scrolling Direction callback:function (index, $currentNode) {//triggered immediately after each scrolling to the new node, CurrentNode is the jquery object for the node currently displayed} }, $this = this, $panel = $this. Find (' >ul '),//scrolling container $panelList = $panel. Find (' >li '), $selectList = $this. Find (' &G T;ol>li '),//select container options = Jquery.extend (defaultopt,options), animatefn,//scrolling animation max = $panel. Find (">li"). Length, The number of nodes to scroll focusindex = 0,//The index of the currently displayed node Nfdscrolltimer = 0,//Timer inanimation = false,//no longer respond to other animations during the animation iswaitting = Fals
 e,//whether there is a pending animation waittingindex;//the pending animation's target index $ ('. Nfdscroll-prev '). Text (Options.prevtext);

 $ ('. Nfdscroll-next '). Text (Options.nexttext);
 There is only one display that does not require a carousel if ($panelList. length <= 1) {return; //The current animation is not finished but the focus has been switched to the next place, and this function is used to protect the currently displayed page and mouse-specified target-consistent processing function dowaitting () {if (iswaitting) {Startscroll (
 Waittingindex);
 }//Start Carousel function Startscroll (toindex) {stopscroll ();
  if (inanimation) {iswaitting = true;
  Waittingindex = Toindex;
The return;//animation process no longer responds to other animations}else{iswaitting = false; } if (Toindex = = undefined) {if (Options.interval > 0) {nfdscrolltimer = SetInterval (function () {Animatefn (to
  Index);
  },options.interval);
  ///Skip to the specified index and then time}else{animatefn (Toindex);
  if (Options.interval > 0) {nfdscrolltimer = SetInterval (function () {animatefn ();
  },options.interval);
 Stop the Carousel function Stopscroll () {clearinterval (Nfdscrolltimer);
  ///left to right scroll animation//parameter toindex:number, scroll to specified index function leftrightanimate (toindex) {//default scrolling mode if (Toindex = = undefined) {
  if (options.deriction = = ' Left ') {Toindex = Focusindex + 1;
  }else{toindex = focusIndex-1;

  } if (Toindex!= focusindex) {inanimation = true;
  The current processing for the last Carousel is var tind = 0;
   if (Toindex >= max) {//The last picture continues to scroll $panel. css ({' paddingleft ': Options.width + ' px '}) $panelList. EQ (0). css ({
  ' Position ': ' absolute ', ' left ': Options.width*toindex + ' px '};
  Tind = 0; }else if (Toindex < 0) {//only in the current picture is the first picture, then click on the previous picture to appear//current for the last carousel when the processing $Panellist.eq (max-1). css ({' position ': ' absolute ', ' left ':-options.width + ' px '});
  Tind = max-1;
  }else{tind = Toindex; ///First switch focus to past $selectList. Filter ('. ' + options.selected). Removeclass (options.selected). End (). EQ (tind). addclass (op 

  tions.selected);

  $panel. Animate ({' marginleft ':-options.width*toindex + ' px '}, options.duration, function () {focusindex = Tind;
   if (Toindex >= max) {//The last picture continues to scroll $panel. css ({' marginleft ': 0, ' paddingleft ': 0});
  $panelList. EQ (0). css ({' position ': ' Static ', ' Left ': ' Auto '}); }else if (Toindex < 0) {//only if the current picture is the first picture, then click on the previous picture to appear $panel. css ({' marginleft ':-options.width*focusindex + ' px ')
   , ' Paddingleft ': 0});
  $panelList. EQ (max-1)-css ({' position ': ' Static ', ' Left ': ' Auto '});
  } options.callback (Focusindex, $panelList. EQ (focusindex));

  Inanimation = false;
  Dowaitting (); }}///Scroll up the animation function topbottomanimate (toindex) {//default scrolling mode if (tOindex = = undefined) {if (options.deriction = = ' top ') {Toindex = Focusindex + 1;
  }else{toindex = focusIndex-1;

  } if (Toindex!= focusindex) {inanimation = true;
  The current processing for the last Carousel is var tind = 0; if (Toindex >= max) {$panel. css ({' paddingtop ': Options.height + ' px '}) $panelList. EQ (0). css ({' Position ':
  ' Absolute ', ' top ': Options.height*toindex + ' px '};
  Tind = 0; }else if (Toindex < 0) {//Only when the current picture is the first picture, and then clicking on the previous picture appears//is currently the last carousel when the processing $panelList. EQ (max-1). css ({' Position ': '
  Absolute ', ' top ':-options.height + ' px '};
  Tind = max-1;
  }else{tind = Toindex; //First switch focus to past $selectList. Filter ('. ' + options.selected). Removeclass (options.selected). End (). EQ (tind) addclass (Opti

  ons.selected);

  $panel. Animate ({' margintop ':-options.height*toindex + ' px '}, options.duration, function () {focusindex = Tind;
   if (Toindex >= max) {$panel. css ({margintop:0, ' paddingtop ': 0}); $panelList. EQ (0). CSS ({' position ': ' Static ', ' top ': ' Auto '}); }else if (Toindex < 0) {//only if the current picture is the first picture, then click on the previous picture to appear $panel. css ({' margintop ':-options.height*focusindex + ' px ')
   , ' Paddingtop ': 0});
  $panelList. EQ (max-1)-css ({' position ': ' Static ', ' top ': ' Auto '});
  } options.callback (Focusindex, $panelList. EQ (focusindex));

  Inanimation = false;
  Dowaitting ();
   
 }}} function Bindevent () {//binding event $this. On (' MouseOver ', function () {stopscroll ();
 }). On (' Mouseout ', function () {startscroll ();
  ). On (' click ', '. Nfdscroll-prev ', function () {stopscroll ();
 Startscroll (focusIndex-1);
  ). On (' click ', '. Nfdscroll-next ', function () {stopscroll ();
 Startscroll (Focusindex + 1);
  }) $selectList. On (' MouseOver ', function () {stopscroll ();
  if (!$ (this). are ('. ' + options.selected)) {Startscroll ($ (this). index ());
 } 
 });
 function init () {$this. css ({position: ' relative ', Overflow: ' Hidden '}); $panel. css ({position: ' relative '}) focusindex = options.startindex;//The default starts from StartIndex scrolling $selectList. EQ (focusindex). addclass (options.selected);//First switch focus to past if ( Options.deriction = = ' Left ' | |  Options.deriction = = ' Right '} {//initialization style, in fact, should not be in the plug-in inside to do the style, should be the user himself to ensure that the style is no problem var Csso = {width:options.width, ' float ':
  ' Left '} $this. css ({width:options.width});//Only the width of the pipe can be if (options.height) {csso.height = Options.height;
  var leng = $panel. Find (' >li '). CSS (Csso). length;
  
  $panel. css ({width:options.width * leng + ' px ', ' marginleft ':-options.width*focusindex + ' px '});
 Animatefn = leftrightanimate; }else if (options.deriction = = ' Top ' | | | options.deriction = = ' Bottom ') {var Csso = {Height:options.height} $this
  . css ({height:options.height});//Only the height of the tube can be if (options.width) {csso.width = Options.width;
  var leng = $panel. Find (' >li '). CSS (Csso). length;

  $panel. css ({height:options.height * leng + ' px ', ' margintop ':-options.height*focusindex + ' px '}); Animatefn = TopbottomAnimate;
  }else{alert (' Plugin only supports scrolling in four directions of Left/right/top/bottom ');
 Return
 } startscroll ();
 } bindevent ();

 Init ();
 return {' Stopscroll ': stopscroll, ' Startscroll ': Startscroll}}});

A complete example of  

<! DOCTYPE html>  

Implementation effect:

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.