作业 :制作简易选项卡 需求说明:请使用“构造函数+原型”的方法制作简易选项卡。 1、选项卡可以自动播放 2、鼠标滑过哪个选项就播放对应选项的内容 3、鼠标离开后,继续按顺序播放 4、注意:播放或滑过哪个选项卡,哪个选项卡的背景颜色变为蓝色
时间: 2023-05-30 16:07:03 浏览: 60
HTML代码:
```html
<div class="tab">
<ul>
<li class="active">选项卡1</li>
<li>选项卡2</li>
<li>选项卡3</li>
</ul>
<div class="content">
<div class="item active">选项卡1的内容</div>
<div class="item">选项卡2的内容</div>
<div class="item">选项卡3的内容</div>
</div>
</div>
```
CSS代码:
```css
.tab {
width: 500px;
margin: 50px auto;
}
.tab ul {
list-style: none;
margin: 0;
padding: 0;
display: flex;
}
.tab li {
flex: 1;
text-align: center;
padding: 10px;
cursor: pointer;
transition: background-color 0.3s;
}
.tab li.active {
background-color: blue;
color: #fff;
}
.tab .content {
border: 1px solid #ccc;
padding: 20px;
}
.tab .item {
display: none;
}
.tab .item.active {
display: block;
}
```
JavaScript代码:
```javascript
function Tab(options) {
this.tab = options.tab;
this.autoPlay = options.autoPlay || false;
this.interval = options.interval || 3000;
this.init();
}
Tab.prototype.init = function() {
var self = this;
var lis = self.tab.querySelectorAll('ul li');
var items = self.tab.querySelectorAll('.item');
var timer = null;
var currentIndex = 0;
// 播放选项卡
function play() {
if (self.autoPlay) {
timer = setInterval(function() {
currentIndex++;
if (currentIndex >= lis.length) {
currentIndex = 0;
}
changeTab(currentIndex);
}, self.interval);
}
}
// 改变选项卡
function changeTab(index) {
currentIndex = index;
for (var i = 0; i < lis.length; i++) {
if (i === index) {
lis[i].classList.add('active');
items[i].classList.add('active');
} else {
lis[i].classList.remove('active');
items[i].classList.remove('active');
}
}
}
// 绑定滑过事件
for (var i = 0; i < lis.length; i++) {
(function(i) {
lis[i].addEventListener('mouseover', function() {
clearInterval(timer);
changeTab(i);
});
lis[i].addEventListener('mouseout', function() {
play();
});
})(i);
}
// 初始播放选项卡
play();
};
var tab = new Tab({
tab: document.querySelector('.tab'),
autoPlay: true,
interval: 3000
});
```