Web37.面向对象实战
2017-11-06 本文已影响5人
FiredEarthMusic
//Tab切换
<script>
function Tab(ct) {
var _this = this;
this.tabLis = ct.querySelectorAll('.tab-header>li');
this.tabPanels = ct.querySelectAll('.tab-container>li');
this.tabLis.forEach(function(tabli) {
tabli.onclick = function(e){
var target = e.target;
var index = [].indexOf.call(_this.tabLis, target);
_this.tabLis.forEach(function(li){
li.classList.remove('active');
})
target.classList.add('active');
_this.tabPanels.forEach(function(panel){
panel.classList.remove('active');
})
_this.tabPanels[index].classList.add('active');
}
})
}
var tab1 = new Tab(document.querySelectorAll('.tab')[0])
var tab2 = new Tab(document.querySelectorAll('.tab')[1])
</script>
//换一种写法
<script>
function Tab(ct){
this.ct = ct;
this.init();
this.bind();
}
Tab.prototype.init = function(){
this.tabLis = this.ct.querySelectorAll('.tab-header>li');
this.tabPanels = this.ct.querySelectAll('.tab-container>li');
}
Tab.prototype.bind = function(){
var _this = this;
this.tabLis = ct.querySelectorAll('.tab-header>li');
this.tabPanels = ct.querySelectAll('.tab-container>li');
this.tabLis.forEach(function(tabli) {
tabli.onclick = function(e){
var target = e.target;
var index = [].indexOf.call(_this.tabLis, target);
_this.tabLis.forEach(function(li){
li.classList.remove('active');
})
target.classList.add('active');
_this.tabPanels.forEach(function(panel){
panel.classList.remove('active');
})
_this.tabPanels[index].classList.add('active');
}
})
}
</script>
//轮播
function Carousel($ct) {
this.$ct = ct
}
Carousel.prototype.init = function(){
var $imgCt = this.$ct.find('.img-ct'),
$preBtn = this.$ct.find('.btn-pre'),
$nextBtn = this.$ct.find('.btn-next'),
$bullet = this.$ct.find('.bullet');
var $firstImg = $imgCt.find('li').first(),
$lastImg = $imgCt.find('li').last();
this.curPageIndex = 0;
this.imgLength = $imgCt.children().length;
this.isAnimate = false;
$imgCt.prepend($lastImg.clone())
$imgCt.append($firstImg.clone())
$imgCt.width($firstImg.width() * $imgCt.children().length)
$imgCt.css({
'left': '-300px'
})
}
Carousel.prototype.bind = function(){
this.$preBtn.on('click', function(e) {
e.preventDefault();
playPre();
})
this.$nextBtn.on('click', function(e) {
e.preventDefault();
playNext();
})
}
Carousel.prototype.playPre = function() {
if (this.isAnimate) return;
this.isAnimate = true;
this.$imgCt.animate({
left: '+=300px'
}, function() {
curPageIndex--;
if (curPageIndex < 0) {
$imgCt.css('left', -(imgLength * $firstImg.width()));
curPageIndex = imgLength - 1
}
})
isAnimate = false;
setBullet()
}
Carousel.prototype.playNext = function() {
}
Carousel.prototype.setBullet = function() {
}
new Carousel($('.carousel'));