效果展示一:
效果展示二:
html
首先设置滑块大小,然后设置渐变背景色,通过超出隐藏来实现滑块渐变色。
<div class="menuList">
<ul>
<li class="menuLi">
<span>菜单1</span>
</li>
<li class="menuLi">
<span>菜单2</span>
</li>
<li class="menuLi">
<span>菜单3</span>
</li>
<li class="menuLi">
<span>菜单4</span>
</li>
<li class="menuLi">
<span>菜单5</span>
</li>
<li class="menuLi">
<span>菜单6</span>
</li>
</ul>
![11754bd2529a4086af1841639b10f3b.png](https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/0da1b9e06f094b3791e0ea067d8de6c3~tplv-k3u1fbpfcp-watermark.image?)
<div id="slider">
<span id="slider2"></span>
</div>
</div>
css(效果一)
*{margin:0;padding:0}
.menuList{
width: 600px;
height: 38px;
display: flex;
flex-direction: column;
position: relative;
margin:0 auto;
}
ul{
list-style: none;
width: 600px;
height: 30px;
display: flex;
}
ul>li{
width: 100px;
height: 30px;
display: flex;
}
ul>li span:nth-child(1){
display: block;
width:100px;
text-align: center;
}
/*滑块区域*/
#slider{
width:100px;
height: 8px;
border-radius: 8px;
overflow: hidden;
transition: all .3s;
position: relative;
bottom: 0;
left: 0px;
}
/* 滑块背景色 */
#slider2{
width: 600px;
height: 8px;
position: absolute;
bottom: 0;
left: 0px;
background: linear-gradient(to right,#FF6600,#CC00FF,lightblue,pink,#FF0000);
}
css 效果二
*{margin:0;padding:0}
.menuList{
width: 600px;
height: 38px;
display: flex;
flex-direction: column;
position: relative;
margin:0 auto;
}
ul{
list-style: none;
width: 600px;
height: 30px;
display: flex;
}
ul>li{
width: 100px;
height: 38px;
display: flex;
line-height: 38px;
}
ul>li span:nth-child(1){
display: block;
width:100px;
text-align: center;
}
#slider{
width:100px;
height: 38px;
border-radius: 28px;
overflow: hidden;
transition: all .3s;
position: absolute;
bottom: 0;
left: 0px;
}
#slider2{
width: 600px;
height: 38px;
position: absolute;
bottom: 0;
left: 0px;
z-index: -1;
background: linear-gradient(to right,#FF6600,#CC00FF,lightblue,pink,#FF0000);
}
js
因为子元素是跟随父元素绝对定位的,所以我们需要同步向相反方向移动渐变背景色。
var menuLi = document.getElementsByClassName('menuLi');
var slider = document.getElementById('slider');
var slider2 = document.getElementById('slider2');
for(let i=0; i<6; i++){
menuLi[i].onclick = function (){
slider.style.marginLeft = i * 100 + 'px'
slider2.style.marginLeft = i * -100 + 'px'
}
}