jQuery背景滑动跟随的导航菜单

快乐打工仔 分类:实例代码

分享一段代码实例,它实现了横向导航菜单效果。

并且导航菜单的背景会跟随鼠标滑动。

代码实例如下:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<title>犀牛前端部落</title>
<style>
div, p, h1, h2, h3, h4, h5, h6, ul, a, {
margin: 0;
padding: 0;
}
.box {
width: 100%;
height: 50px;
background: #555;
}
.nav:after {
content: '';
display: block;
clear: both;
}
.nav {
position: relative;
width: 1100px;
height: 50px;
margin: 0 auto;
overflow: hidden;
}
.nav > li {
float: left;
height: 50px;
font-size: 20px;
color: #fff;
list-style: none;
font-weight: bold;
line-height: 50px;
padding: 0 30px;
position: relative;
z-index: 10;
display: inline-block;
cursor: pointer;
overflow: hidden;
}
.nav > .active {
background: red;
padding: 0 50px;
}
.leftbox {
position: absolute;
top: 0;
left: 40px;
background: #f00;
width: 140px;
height: 50px;
z-index: 0;
}
</style>
<script src='http://libs.baidu.com/jquery/2.0.0/jquery.js'></script>
<script>
$(document).ready(function() {
$('li').mouseover(function() {
li_W = parseInt($(this).width()); //当前li的宽
li_pad = $(this).css('padding'); //当前li的内边距
li_pad = (li_pad.split('px')[1]) * 2; //当前li的内边距
W = li_W + li_pad + 'px'; //要设置的移动背景的宽
ul_left = $('.nav').offset().left;
li_left = $(this).offset().left;
var L = (li_left - ul_left);
$('.leftbox').stop().animate({
left: L + 'px'
}, 100, function() {
$('.leftbox').css('width', W); //设置移动背景的宽
});
});
$('ul').mouseout(function(e) {
var ul = $('ul')[0];
var e = e || window.event;
if (!isMouseLeaveOrEnter(e, ul)) {
return false;
}
//console.log("=============");
$('.leftbox').css('width', '100px').stop().animate({
left: '40px'
}, 500);
});
function isMouseLeaveOrEnter(e, handler) {
var reltg = e.relatedTarget ? e.relatedTarget : e.type == 'mouseout' ? e.toElement : e.fromElement;
while (reltg && reltg != handler) {
reltg = reltg.parentNode;
}
return (reltg != handler);
}
})
</script>
</head>
<body>
<div class="box">
<ul class="nav">
<div class="leftbox"></div>
<li class="active">新闻</li>
<li>网页</li>
<li>资讯</li>
<li>娱乐</li>
<li>军事</li>
<li>互联网</li>
<li>网页</li>
<li>资讯</li>
<li>娱乐</li>
<li>军事</li>
<li>互联网</li>
</ul>
</div>
</body>
</html>

jQuery背景滑动跟随的导航菜单,这样的场景在实际项目中还是用的比较多的,关于jQuery背景滑动跟随的导航菜单就介绍到这了。

jQuery背景滑动跟随的导航菜单属于前端实例代码,有关更多实例代码大家可以查看

回复

我来回复
  • 暂无回复内容