Scrollerota jQuery плагин
автор: 2Web16 октября, 2011
Вы задумывались когда-нибудь, как важно для пользователя юзабилити того или иного слайдера?
Если ответ положительный, то просто посмотрите на рабочий пример слайдера Scrollerota.
О том как он работает и как его внедрить на ваш сайт, смотрите под катом.
Впечатляет?
Тогда смотрим jQuery код этого слайдшоу плагина:
/**
* jQuery.scrollerota
* Version 1.0
* Copyright (c) 2011 c.bavota - http://bavotasan.com
* Dual licensed under MIT and GPL.
* Date: 02/04/2011
**/
(function($){
$.fn.scrollerota = function(options) {
// setting the defaults
// $("#scrollerota").scrollerota({ width: 500, height: 333, padding: 10, speed: 2000, timer: 5000, slideshow: true, easing: "easeInOutQuart" });
var defaults = {
width: 500,
height: 333,
padding: 10,
speed: 2000,
timer: 5000,
slideshow: true,
easing: 'easeInOutQuart'
};
var options = $.extend(defaults, options);
// and the plugin begins
return this.each(function() {
// initializing the variables
var obj, images, texts, first, last, imglimit, txtlimit, itemNum, totalWidth, totalHeight, txtTop, imgLeft, txtMove, imgMove;
// creating the object variable
obj = $(this);
images = obj.find("ul.images");
texts = obj.find("ul.text");
// cloning the first and last item to create the infinite scrolling
first = images.find("li:first");
last = images.find("li:last");
first.clone().appendTo(images);
last.clone().prependTo(images);
first = texts.find("li:first");
last = texts.find("li:last");
first.clone().appendTo(texts);
last.clone().prependTo(texts);
// figuring out the total width and height for the images and the text boxes
itemNum = images.find("li").length;
totalWidth = itemNum * options.width;
totalHeight = itemNum * options.height;
imglimit = -((itemNum - 1) * options.width);
txtlimit = -((itemNum - 1) * options.height);
// setting the CSS for the image elements
images
.css({
width: totalWidth+"px",
height: options.height+"px",
left: -options.width+"px"
})
.find("li").css({ width: options.width+"px", height: options.height+"px" })
.end()
.find("li img").css({ width: options.width+"px", height: options.height+"px" });
// setting the CSS for the text elements
texts
.css({
height: totalHeight+"px",
top: -options.height+"px"
})
.find("li").css({ height: (options.height-(options.padding*2))+"px", padding: options.padding+"px" });
// slideshow functionality
if(options.slideshow) {
// creating the loop for the slideshow
loop = setTimeout(function() { autoScroll(1,1); }, options.timer);
// adding the controls for the slideshow
obj.append('<div class="controls"><a href="javascript:void(0)" class="prev"></a> <a href="javascript:void(0)" class="play"></a> <a href="javascript:void(0)" class="pause"></a> <a href="javascript:void(0)" class="next"></a></div>')
// the pause click function
obj.find(".pause").live("click", function() {
clearTimeout(loop);
obj.find(".play, .pause").toggle();
});
// the play click function
obj.find(".play").live("click", function() {
loop = setTimeout(function() { autoScroll(1, 1); }, options.timer);
obj.find(".play, .pause").toggle();
});
} else {
// adding the next and previous controls
obj.append('<div class="controls"><a href="javascript:void(0)" class="prev"></a> <a href="javascript:void(0)" class="next"></a></div>')
}
// the next and previous click function
obj.find(".next, .prev").live("click", function() {
if($(this).hasClass("next")) {
autoScroll(1,0);
} else {
autoScroll(0,0);
}
if(options.slideshow) {
clearTimeout(loop);
obj.find(".play").show();
obj.find(".pause").hide();
}
});
// the autoScroll function
function autoScroll(next, auto) {
txtTop = texts.css('top').replace("px", "");
imgLeft = images.css('left').replace("px", "");
txtMove = (next) ? txtTop - options.height : parseInt(txtTop) + parseInt(options.height);
imgMove = (next) ? imgLeft - options.width : parseInt(imgLeft) + parseInt(options.width);
// animating the text
texts.not(':animated').animate({ top: txtMove+"px" }, options.speed, options.easing, function() {
// check if we have reach the end in either direction of the scroll
if(txtMove==txtlimit) { texts.css({ top: -options.height+"px" }); }
if(txtMove==0) { texts.css({ top: (txtlimit+options.height)+"px" }); }
});
// animating the images
images.not(':animated').animate({ left: imgMove+"px" }, options.speed, options.easing, function() {
// check if we have reach the end in either direction of the scroll
if(imgMove==imglimit) { images.css({ left: -options.width+"px" }); }
if(imgMove==0) { images.css({ left: (imglimit+options.width)+"px" }); }
});
// continuing the loop if the slideshow is activated
if(auto && options.slideshow) { loop = setTimeout(function() { autoScroll(1,1); }, options.timer); }
}
});
};
})(jQuery);
Собственно CSS:
#scrollerota {
width: 500px;
height: 333px;
overflow: hidden;
position: relative;
}
#scrollerota ul.text {
list-style: none;
width: 200px;
background: url(images/pixel.png);
position: absolute;
top: 0;
left: 0;
padding: 0;
margin: 0;
color: #fff;
font-size: 14px;
line-height: 20px;
}
#scrollerota ul.text li {
overflow: hidden;
}
#scrollerota a.readmore {
background: #666;
border: 1px solid #777;
padding: 5px 0;
text-align: center;
color: #fff;
clear: both;
display: block;
width: 80px;
margin-top: 16px;
text-decoration: none;
font-size: 12px;
line-height: 17px;
}
#scrollerota a:hover.readmore {
background: #888;
border: 1px solid #999;
text-decoration: none;
}
#scrollerota ul.images {
list-style: none;
position: absolute;
top: 0;
left: 0;
padding: 0;
margin: 0;
}
#scrollerota ul.images li {
float: left;
}
#scrollerota .controls {
position: absolute;
bottom: 10px;
right: 10px;
}
#scrollerota .controls a {
width: 22px;
height: 22px;
display: block;
float: left;
background: url(images/controls.png) no-repeat;
}
#scrollerota .controls .prev {
background-position: 0 -22px;
}
#scrollerota .controls .next {
background-position: -23px -22px;
}
#scrollerota .controls .play {
background-position: -23px 0;
display: none;
}
И конечо HTML структура должна выглядеть следующим образом:
<div id="scrollerota">
<ul class="images">
<li><img src="images/image1.jpg" /></li>
<li><img src="images/image2.jpg" /></li>
<li><img src="images/image3.jpg" /></li>
</ul>
<ul class="text">
<li>Nullam rutrum, nibh sit amet sodales luctus, mauris est placerat justo, molestie gravida lorem enim eu sapien. Curabitur porttitor lobortis felis ac ultricies. Nulla velit ipsum, lobortis ac bibendum vitae, aliquam at metus.<a href="#" class="readmore">Read more</a></li>
<li>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Etiam et eros nisl. Etiam vehicula lobortis pharetra. Integer ut ipsum risus.<a href="#" class="readmore">Read more</a> </li>
<li>Nulla facilisis felis vitae leo condimentum quis adipiscing turpis rhoncus. Sed id lacus libero, ut accumsan lacus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.<a href="#" class="readmore">Read more</a> </li>
</ul>
</div>
Чтобы запустить этот плагин на вашем сайте, прежде всего проверьте подключение jQuery в шапке сайта и не забудьте включить перед закрывающим тэгом body следующий код:
<script type="text/javascript">
$("#scrollerota").scrollerota({
width: 500,
height: 333,
padding: 10,
speed: 2000,
timer: 5000,
slideshow: true,
easing: 'easeInOutQuart'
});
</script>
Далее список параметров, нуждающихся в пояснении:
- width — полная ширина слайдшоу-окна
- height — полная высота слайдшоу-окна
- padding — отступ по кругу для текстового блока
- speed — время в миллисекундах анимации слайда
- timer — пауза между слайдами (игнорируется если слайдер выключен)
- slideshow — установите false, если хотите отключить автоматическое слайдшоу
- easing — тип анимации
Если вы захотите использовать продвинутые типы анимации, то вам нужно скачать последнюю библиотеку jQuery UI. Или можете обойтись базовыми типами анимаций: линейная и качели.
Источник: bavotasan.com
PS. Сможет ли фрилансер или вебмастер, которые не работают на дядю, взять кредит на жилье? Могут возникнуть трудности с оформлением?
Здравствуйте.
Вопрос возник, куда и как вставлять jQuery код...?
Скачайте исходники и посмотрите исходный код html файла. Все сразу поймете.