JSFiddle - React, Tailwind, and code Playground
by Kiwoong Jang
HTML
<div id="bannerWrap">
<div id="banners">
<ul>
<li><a href="#"><img src="http://thumbs.dreamstime.com/thumblarge_329/1225732979w0W0H1.jpg" alt="banner1" /></a></li>
<li><a href="#"><img src="http://thumbs.dreamstime.com/thumblarge_251/1206360421cyuy49.jpg" alt="banner2" /></a></li>
<li><a href="#"><img src="http://thumbs.dreamstime.com/thumblarge_250/1206007964EHVWMJ.jpg" alt="banner3" /></a></li>
</ul>
</div>
<p id="controller">
<!-- 배너의 갯수에 따라 span 이 자동으로 추가 생성됨 -->
</p>
</div>
CSS
#bannerWrap { }
#banners { width: 400px; height: 100px; overflow: hidden; }
#banners ul { width: 3000em; overflow: hidden; }
#banners ul li { float: left; }
p#controller { width: 400px; overflow: hidden; }
p#controller span { display: block; float: left; width: 10px; height: 10px; margin: 0 2px; cursor: pointer; background: red; }
p#controller span.on { background: blue; }
JavaScript
function rollBanner(options) {
var self = this;
this.banner = options.banner;
this.items = this.banner.children("li");
this.controller = options.controller;
this.width = options.width;
this.speed = options.speed || 2000;
this.delay = options.delay || 2000;
this.current = 0, this.timer = null;
this.items.eq(0).clone().appendTo(this.banner);
self.setControl();
self.timer = setTimeout(function() { self.rolling(); }, self.delay);
};
rollBanner.prototype.setControl = function() {
var self = this;
self.items.each(function(idx) {
self.controller.append("<span class='" + ((idx == 0) ? "on" : "") + "'></span>");
});
self.controls = self.controller.children("span");
self.controls.each(function(idx) {
$(this).bind("click", function() {
self.rolling(idx);
});
});
};
rollBanner.prototype.rolling = function(idx) {
var self = this, speed = self.speed;
clearTimeout(self.timer);
self.banner.stop();
if(self.current >= self.items.length) {
self.current = 0;
self.banner.css({ marginLeft: 0 });
}
if(idx != undefined) {
self.current = idx - 1;
speed = self.speed / 2;
}
self.banner.animate({ marginLeft: self.width * (self.current + 1) * -1 }, speed, 'linear', function() {
self.controls.removeClass("on");
self.current ++;
self.controls.eq((self.current >= self.controls.length) ? 0 : self.current).addClass("on");
self.timer = setTimeout(function() { self.rolling(); }, self.delay);
});
};
new rollBanner({ banner: $("#banners > ul"), controller: $("#controller"), width: 400, speed: 1000, delay: 1000 });