js原生代码实现导航栏动画效果。
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jsNav</title>
</head>
<body>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
body{
background: black;
}
#nav{
width: 720px;
height: 26px;
border:1px greenyellow solid;
border-radius: 10px;
margin: 0 auto;
margin-top: 250px;
padding-left: auto;
padding-right: auto;
position: relative;
}
ul{
list-style: none;
position: absolute;
width: 720px;
height: 26px;
}
li{
display: inline;
float: left;
}
a{
text-decoration: none;
display: block;
color:greenyellow;
font-size: 20px;
width: 90px;
height: 26px;
text-align: center;
}
#move{
position: absolute;
background: pink;
/*border:1px solid;*/
border-radius: 10px;
height: 26px;
width: 90px;
}
</style>
<div id="nav">
<div id="move"></div>
<ul>
<li><a id="a1" href="#">腾讯新闻</a></li>
<li><a href="#">搜狗新闻</a></li>
<li><a href="#">朝闻天下</a></li>
<li><a href="#">新闻联播</a></li>
<li><a href="#">明日之子</a></li>
<li><a href="#">罗马假日</a></li>
<li><a href="#">腾讯视频</a></li>
<li><a href="#">琅琊榜</a></li>
</ul>
</div>
<script>
function move(ID,final_x,final_y,interval) {
var Div=document.getElementById("move");
if(Div.movement){
clearInterval(Div.movement);
}
if(!Div.style.left){
Div.style.left="0px";
}
if(!Div.style.top){
Div.style.top="0px";
}
var xpos=parseInt(Div.style.left);
var ypos=parseInt(Div.style.top);
var dist=0;
if(xpos==final_x&&ypos==final_y){
return true;
}
if(xpos<final_x){
dist=Math.ceil((final_x-xpos)/10);
xpos=xpos+dist;
}
if(xpos>final_x){
dist=Math.ceil((xpos-final_x)/10);
xpos=xpos-dist;
}
// if(ypos<final_y){
// dist=Math.ceil((final_y-ypos)/10);
// ypos=ypos+dist;
// }
// if(ypos>final_y){
// dist=Math.ceil((ypos-final_y)/10);
// ypos=ypos-dist;
// }
Div.style.left=xpos+"px";
Div.style.top=ypos+"px";
var repeat="move('"+ID+"',"+final_x+","+final_y+","+interval+")";
Div.movement=setTimeout(repeat,interval);
}
function pre() {
var Div=document.getElementById("move");
var links=document.getElementsByTagName("a")
var ul=document.getElementsByTagName("ul")
ul[0].onmouseout=function (ev) {
move("Div",0,0,10)
}
links[0].onmouseover=function () {
move("Div",0,0,10)
}
links[1].onmouseover=function () {
move("Div",90,0,10)
}
links[2].onmouseover=function () {
move("Div",180,0,10)
}
links[3].onmouseover=function () {
move("Div",270,0,10)
}
links[4].onmouseover=function () {
move("Div",360,0,10)
}
links[5].onmouseover=function () {
move("Div",450,0,10)
}
links[6].onmouseover=function () {
move("Div",540,0,10)
}
links[7].onmouseover=function () {
move("Div",630,0,10)
}
}
window.onload=pre();
</script>
</body>
</html>