上面的效果是一个具有弹性效果的选择按钮,可以实现比较华丽的效果。具体的设置可以通过调整CSS效果来实现想要的效果。
下面是源码和解释:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
padding: 0;
margin: 0;
}
#box{
width: 500px;
height: 50px;
position: absolute;
left: 20px;
top: 50px;
}
#box #content{
z-index: 0;
}
#box #content ul{
display: inline-block;
}
#box #content ul li{
display: inline-block;
width: 90px;
height: 50px;
float: left;
margin-right:5px;
background: seagreen;
text-align: center;
line-height: 50px;
}
#bar{
width: 90px;
height: 50px;
position: absolute;
top: 0;
z-index: 999;
overflow: hidden;
background: rgba(141, 74, 255, 0.6);
border-radius: 20px;
}
#bar ul {
display: inline-block;
width: 500px;
position: absolute;
}
#bar ul li{
display: inline-block;
width: 90px;
height: 50px;
list-style-type: none;
color: whitesmoke;
text-align: center;
line-height: 50px;
float: left;
margin-right:5px;
}
</style>
</head>
<body>
<div id="box">
<div id="bar">
</div>
<div id="content">
<ul>
<li>home</li>
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
</ul>
</div>
</div>
</body>
<script>
window.onload= function () {
var bar=document.getElementById("bar");//获取遮罩层
var box=document.getElementById("box");//获取整体
var liList=box.getElementsByTagName("li");//获取标签
var content=document.getElementById("content");//获取标签容器
var time=null;//用于存放遮罩层运动的定时器
var time2=null;//用于存放设置返回原点的定时器,即一个节流函数。
var speed=0;//速度初始
bar.innerHTML+=content.innerHTML;//动态的为bar添加内容,可以实现字母跟随遮罩层滚动的效果,前提是要让bar中的标签和content中的标签通过CSS完全设置重合。
var barUl=bar.getElementsByTagName("ul")[0];//添加后获取bar内部ul对象,用来动态调整位置。
for(var i=0;i<liList.length;i++){
liList[i].onmouseover= function () {
clearInterval(time2);
move(bar,this.offsetLeft);
};
liList[i].onmouseout= function () {//当鼠标mouseout的的时候,遮罩层返回原点,通过函数节流设置。
time2=setTimeout(function () {
move(bar,0);
},300);
}
}
bar.onmouseover= function () {//当遮罩层mouseover的时候,停止效果。
clearInterval(time2);
};
bar.onmouseout= function () {//当遮罩层mouseout的的时候,遮罩层返回原点,通过函数节流设置。
time2=setTimeout(function () {
move(bar,0);
},300);
};
var move= function (obj, target) {
clearInterval(time);
time=setInterval(function () {
speed+=(target-obj.offsetLeft)/6;//弹性速度
speed*=0.7;//弹性摩擦系数
if(Math.abs(speed)<1 && Math.abs(target-obj.offsetLeft)<1){//当速度绝对值小于1并且初始值和结束值之间的距离小于1的时候,停止运动。并且设置最终效果。
clearInterval(time);
obj.style.left=target+'px';
barUl.style.left=-obj.offsetLeft+'px';//为了实现滚动的效果,需要实现bar内部的ul对象与bar实现反向运动。
speed=0;
}else{
obj.style.left=obj.offsetLeft+speed+'px';
barUl.style.left=-obj.offsetLeft+'px';
}
},30)
}
}
</script>
</html>