先看一张效果图
这里点击左右两边的箭头可以实现菜单的左右滑动,滑动到最左边或者最右边会有一个回弹的效果,就是一个无更多内容的效果。下图是点击左侧按钮,菜单向左滑动一个tab的效果
emmm... 话说的差不多了,小二,上代码(有点粗糙)
先是css:
* {
margin: 0;
padding: 0;
}
.content-wrap {
display: flex;
align-items: center;
margin: 100px;
background: #020a17;
opacity: 0.7;
width: 500px;
overflow: hidden;
border: 1px solid #003399;
border-radius: 35px;
padding: 0 10px;
line-height: 50px;
}
.tab-wrap {
height: 50px;
width: 400px;
display: inline-block;
/* background: #bfa; */
line-height: 50px;
position: relative;
overflow: hidden;
flex: 1;
margin: 0 10px;
}
.tab-list {
white-space: nowrap;
position: absolute;
font-size: 0;
}
.tab-list span {
background: #554CCD;
font-size: 16px;
margin: 0 5px;
padding: 3px;
border-radius: 5px;
}
.to-left,
.to-right {
display: inline-block;
width: 23px;
height: 20px;
/* font-size: 36px;
color: #554CCD; */
cursor: pointer;
background-repeat: no-repeat;
background-size: 23px 20px;
background-position: center;
}
.to-left {
background-image: url(img/toLeft.png);
}
.to-right {
background-image: url(img/toRight.png);
}
接着是HTML:
<div class="content-wrap">
<span class="to-left"></span>
<div class="tab-wrap">
<div class="tab-list">
<span>英雄联盟(LOL)</span>
<span>穿越火线(CF)</span>
<span>地下城勇士(DNF)</span>
<span>逆战</span>
<span>刺激战场</span>
<span>敲代码</span>
<span>玩游戏</span>
<span>学习</span>
<span>吃饭</span>
<span>买东西</span>
</div>
</div>
<span class="to-right"></span>
</div>
然后是JS(这里用了jquery,使用时自行引入):
var handleNum = 0 // 点击次数
var widthArr = [] // 存放当前每一个tab宽度
var elChildren = $('.tab-list').children('span')
for (var i = 0, ilen = elChildren.length; i < ilen; i++) {
widthArr.push($('.tab-list').children('span')[i].offsetWidth + 10) // 10是当前span的margin
}
$('.to-left').on('click', function() {
animateTabs('left', $('.tab-list'))
})
$('.to-right').on('click', function() {
animateTabs('right', $('.tab-list'))
})
function animateTabs(type, $el) {
var elWidth = $el[0].clientWidth // 内部菜单的宽度
var wrapWidth = $('.tab-wrap')[0].clientWidth // 外层包裹的宽度
var canmove = elWidth - wrapWidth // 可以移动的距离
currleft = $el[0].offsetLeft // 当前向左偏移的距离
if (type === 'left') { // 向左
currleft = Math.abs(currleft) + widthArr[handleNum]
$el.stop().animate({left: -currleft + 'px'}, 300, function() {
handleNum++
if (currleft >= canmove) {
handleNum = $el.children('span').length - 1
$el.stop().animate({left: -canmove + 'px',})
}
})
} else { // 向右
currleft = currleft + widthArr[handleNum]
$el.stop().animate({left: currleft + 'px'}, 300, function() {
handleNum--
if (currleft >= 0) {
handleNum = 0
$el.stop().animate({left: 0 + 'px'})
}
})
}
}
这样一来,功能大概实现了,至少看起来是那么回事,可以参考,看着不舒服的我接着优化。^-^