跟随光标下划线导航插件

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<ul id="nav">
<li>首页</li>
<li>导航</li>
<li>导航</li>
<li>导航</li>
<li>导航</li>
</ul>
<style type="text/css">
*{
margin:0;
padding: 0;
}
body,html{
width:100%;
height: 100%;
}
ul{
width:100%;
height:50px;
background-color:rgba(12,16,33,.9);;
padding:0 10px;
}
li{
list-style: none;
padding:0 10px;
height:100%;
float:left;
color:#fff;
line-height: 50px;
}
li:hover{
background:rgba(12,16,33,.2);
cursor:pointer;
}
</style>
<script type="text/javascript">
var navFollow;
navFollow=function () {
var el=arguments[0];
if(!el){
console.error('element is not found !');
return;
}
if(!document.getElementById(el)){
console.error('param is not a dom node !')
return;
}
if(el.childNodes==0){
console.error('element has no children !');
return;
}
var element=document.getElementById(el);
var color=arguments[1];
var child=element.firstChild;
element.style.position='relative'
if(child.nodeType==3){
child=child.nextSibling
}
var width=child.clientWidth;
var left=child.offsetLeft;
var height=child.scrollHeight;
var div=document.createElement('div');
div.style.height='6px';
div.style.width=width+'px';
div.style.background=color||'rgba(47,140,254,.4)'
div.style.position='absolute';
div.style.left=left+'px';
div.style.top=height-6+'px';
div.style.transition='all .6s';
document.getElementById('nav').appendChild(div);
//console.log(element.childNodes)获取所有子元素
var children=element.children;//获取直接子元素
console.log(children)
for(var i=0;i<children.length;i++){
children[i].onmouseover=function () {
div.style.left=this.offsetLeft+'px';
div.style.width=this.clientWidth+'px';
}
children[i].onmouseout=function () {
div.style.left=left+'px';
div.style.width=width+'px';
}
children[i].onclick=function () {
left=this.offsetLeft;
width=this.clientWidth;
div.style.left=this.offsetLeft+'px';
div.style.width=this.clientWidth+'px';
}
}
};
navFollow('nav')
//该插件接收2个参数:元素id,下划线的背景色
</script>
</body>
</html>

posted @ 2017-10-30 13:45  lyls  阅读(136)  评论(0编辑  收藏  举报