首页 > 代码库 > 导航栏背景移动

导航栏背景移动

<!doctype html>
<html class="no-js" lang="">

<head>
<meta charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Untitled Document</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="apple-touch-icon" href="http://www.mamicode.com/apple-touch-icon.png">
<!-- Place favicon.ico in the root directory -->
<link rel="stylesheet" type="text/css" href="http://www.mamicode.com/style.css">
<script src="http://www.mamicode.com/jquery-1.11.3.js"></script>
<script>
$(function(){
$(‘nav ul li‘).mouseenter(function(){
var _left=$(this).position().left;
var _width=$(this).width()+40;
$(‘.nav-bg‘).css("left",_left);
$(‘.nav-bg‘).css("width",_width);
});
$(‘nav‘).mouseleave(function(){

var _left=$(‘nav ul li.on‘).position().left;
var _width=$(‘nav ul li.on‘).width()+40;
$(‘.nav-bg‘).css("left",_left);
$(‘.nav-bg‘).css("width",_width);

})
})
</script>
</head>
<style>
body,html,ul{margin: 0px;padding: 0px;}
a{text-decoration: none;}
header{width: 100%;height: 40px;background: #ddd;line-height: 40px;}
nav{width: 1200px;margin: auto;position: relative;}
nav ul {position:relative;z-index: 1;overflow: hidden;}
nav ul li{width:auto;padding: 0px 20px; float: left;list-style: none;cursor: pointer;text-align: center;height: 40px;line-height: 40px;}
.nav-bg{height: 40px;background: #333;position: absolute;left: 0px;opacity: 0.2;transition-duration: .5s;z-index: 0;}
</style>
<body>

<header>
<nav>
<div class="nav-bg"></div>
<ul>
<li class="on"><a href="http://www.mamicode.com/#">栏目标题</a></li>
<li><a href="http://www.mamicode.com/#">栏目标题</a></li>
<li><a href="http://www.mamicode.com/#">栏目标题</a></li>
<li><a href="http://www.mamicode.com/#">栏目标题</a></li>
</ul>
</nav>

</header>
</body>
</html>

导航栏背景移动