Плагин Cycle для библиотеки jQuery. Часть 1

Плагин Cycle для библиотеки jQuery предназначен для создания слайдшоу на сайте. Небольшой по размеру, но при этом позволяет добавить множество визуальных эффектов при смене кадров. Слайдшоу запускается вызовом метода cycle() для контейнера элементов, участвующих в показе. Хотя я говорю “слайдшоу”, на самом деле можно организовать ротацию любых элементов в контейнере.

Плагин Cyrcle поддерживает множество опций для индивидуальной настройки слайдшоу. Опции по умолчанию могут быть переопределены путем передачи методу cyrcle() объекта, содержащего параметры настройки.

// override these globally if you like
$.fn.cycle.defaults = {
    fx:           'fade', // one of: fade, shuffle, zoom, scrollLeft, etc
    timeout:       4000// milliseconds between slide transitions (0 to disable auto advance)
    continuous:    0,     // true to start next transition immediately after current one completes
    speed:         1000// speed of the transition (any valid fx speed value)
    speedIn:       null// speed of the 'in' transition
    speedOut:      null// speed of the 'out' transition
    next:          null// id of element to use as click trigger for next slide
    prev:          null// id of element to use as click trigger for previous slide
    prevNextClick: null// callback fn for prev/next clicks:  function(isNext, zeroBasedSlideIndex, slideElement)
    pager:         null// id of element to use as pager container
    pagerClick:    null// callback fn for pager clicks:  function(zeroBasedSlideIndex, slideElement)
    pagerEvent:   'click', // event which drives the pager navigation
    pagerAnchorBuilder: null, // callback fn for building anchor links
    before:        null// transition callback (scope set to element to be shown)
    after:         null// transition callback (scope set to element that was shown)
    end:           null// callback invoked when the slideshow terminates (use with autostop or nowrap options)
    easing:        null// easing method for both in and out transitions
    easeIn:        null// easing for "in" transition
    easeOut:       null// easing for "out" transition
    shuffle:       null// coords for shuffle animation, ex: { top:15, left: 200 }
    animIn:        null// properties that define how the slide animates in
    animOut:       null// properties that define how the slide animates out
    cssBefore:     null// properties that define the initial state of the slide before transitioning in
    cssAfter:      null// properties that defined the state of the slide after transitioning out
    fxFn:          null// function used to control the transition
    height:       'auto', // container height
    startingSlide: 0,     // zero-based index of the first slide to be displayed
    sync:          1,     // true if in/out transitions should occur simultaneously
    random:        0,     // true for random, false for sequence (not applicable to shuffle fx)
    fit:           0,     // force slides to fit container
    pause:         0,     // true to enable "pause on hover"
    pauseOnPagerHover: 0, // true to pause when hovering over pager link
    autostop:      0,     // true to end slideshow after X transitions (where X == slide count)
    autostopCount: 0,     // number of transitions (optionally used with autostop to define X)
    delay:         0,     // additional delay (in ms) for first transition (hint: can be negative)
    slideExpr:     null// expression for selecting slides (if something other than all children is required)
    cleartype:     0,     // true if clearType corrections should be applied (for IE)
    nowrap:        0      // true to prevent slideshow from wrapping
};

Для начала подключим в разделе head HTML-страницы три JavaScript-файла:

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.cycle.all.js?v2.11"></script>
<script type="text/javascript" src="js/jquery.easing.1.1.1.js"></script>

HTML и CSS:

<div class="pics">
    <img src="images/beach1.jpg" width="200" height="200" />
    <img src="images/beach2.jpg" width="200" height="200" />
    <img src="images/beach3.jpg" width="200" height="200" />
</div>
.pics { 
    height232px
    width:   232px
    padding: 0
    margin0
}
 
.pics img { 
    padding: 15px
    border1px solid #ccc
    background-color: #eee
    width200px;
    height: 200px;
    top0;
    left: 0
}

Выбираем эффект перехода:

  • blindX
  • blindY
  • blindZ
  • cover
  • curtainX
  • curtainY
  • fade
  • fadeZoom
  • growX
  • growY
  • scrollUp
  • scrollDown
  • scrollLeft
  • scrollRight
  • scrollHorz
  • scrollVert
  • shuffle
  • slideX
  • slideY
  • toss
  • turnUp
  • turnDown
  • turnLeft
  • turnRight
  • uncover
  • wipe
  • zoom

Задать эффект перехода можно либо путем передачи методу cyrcle() строки с названием эффекта, либо передав методу объект настроек, где будет определено свойство fx в значении выбранного эффекта (’cover’, ‘fade’ и т.п.).

$('#s1').cycle('fade');

$('#s2').cycle({
    fx: 'scrollDown'
});

Следующий шаг - выбор скорости смены кадров и продолжительность эффекта перехода:

  • speed - продолжительность в миллисекундах эффекта перехода;
  • timeout - количество миллисекунд между сменами кадров.
$('#s3').cycle({
    fx:    'fade',
    speed:  2500
});
$('#s4').cycle({
    fx:      'scrollDown',
    speed:    300,
    timeout:  2000
});

Кроме упомянутых, можно выбрать множество других опций, например pause и random:

  • pause - остановить слайдшоу при наведении указателя мышки;
  • random - показывать картинки в случайном порядке.
$('#s5').cycle({
    fx:    'fade',
    pause:  1
});
$('#s6').cycle({
    fx:     'scrollDown',
    random:  1
});

Ссылки по теме:

Один комментарий

  1. Vitaly:

    Хорошое описание с примерами. Спасибо!

Оставьте свой отзыв