<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>仿京东主页菜单滚动二级菜单跟随置顶</title>
</head>
<style>
*{
padding: 0;
margin: 0;
}
ul{
list-style-type: none;
padding: 0;
margin: 0;
}
.width1200{
width: 1200px;
margin: 0 auto;
}
body{
background-color: #f4f4f4;
}
.box{
position: relative;
}
.box-left{
width: 190px;
overflow: hidden;
padding: 10px 0;
height: 450px;
background-color: #fefefe;
color: #636363;
margin-top: 10px;
}
.box-left li{
line-height: 25px;
font-size: 14px;
color: #333;
cursor: pointer;
padding: 0 15px;
}
.box-absoute{
position: absolute;
left: 190px;
border: 1px solid #ccc;
top: 0;
width: 800px;
min-height: 468px;
background-color: #fff;
box-shadow: 2px 0 5px rgba(0,0,0,.3);
-webkit-transition: top .25s ease;
transition: top .25s ease;
display: none;
}
.box-item{
padding: 20px;
height: 500px;
display: none;
}
</style>
<body>
<div id="top" style="height: 400px; background-color: red;"></div>
<div class="width1200">
<div class="box">
<div class="box-left">
<ul>
<li>
家用电器
</li>
<li>
手机/运营商/数码
</li>
<li>
电脑/办公
</li>
<li>
家居/家具/家装/厨具
</li>
<li>
男/装/童/内衣
</li>
<li>
房产/汽车/汽车用品
</li>
<li>
母婴/玩具乐器
</li>
<li>
食品/酒类/生鲜/特产
</li>
<li>
艺术/礼品鲜花/农资绿植
</li>
<li>
医
</li>
</ul>
</div>
<div class="box-absoute">
<div class="box-item item-1">
1
</div>
<div class="box-item item-2">
2
</div>
<div class="box-item item-3">
3
</div>
<div class="box-item item-4">
4
</div>
<div class="box-item item-5">
5
</div>
<div class="box-item item-6">
6
</div>
<div class="box-item item-7">
7
</div>
<div class="box-item item-8">
8
</div>
<div class="box-item item-9">
9
</div>
<div class="box-item item-10">
10
</div>
</div>
</div>
</div>
<div style="height: 800px; background-color: yellow;"></div>
<script src="jquery.min.js"></script>
<script>
//获取box在当前视口的相对偏移
var BoxOffset = $(“.box”).offset().top;
//导航栏hover事件
$(“.box-left li”).each(function(i){
var i = $(this).index();
$(this).hover(function(){
//先隐藏所有$(“.box-item”)
$(“.box-item”).hide();
//根据下标显示$(“.box-item”)
shows($(“.box-absoute”),$(“.box-item”),i);
//根据子元素下标给父元素$(“.box-absoute”)赋值ID
$(“.box-absoute”).attr(“id”,i);
//判断滚动条滚动到Box元素位置执行操作
if($(window).scrollTop() >= BoxOffset){
//获取窗口距离BOX视口的距离
var cssTop = $(window).scrollTop() - BoxOffset;
//console.log(cssTop);
//设置top值
$(“.box-absoute”).css({
“top”: cssTop
})
}else{
$(“.box-absoute”).css({
“top”: “0”
})
}
},function(){
//鼠标离开隐藏所有
hides($(“.box-absoute”),$(“.box-item”),i)
})
});
//导航栏详情
$(“.box-absoute”).hover(function(index) {
//获取赋值后的ID
var idAttr = $(this).attr(“id”);
//自己显示
$(this).show();
//根据自身的ID,用eq显示对应的子元素
$(this).children().eq(idAttr).show();
}, function() {
//鼠标离开隐藏所有
$(this).hide();
});
//显示
function shows(father,son,i){
father.show();
father.find(son).eq(i).show()
}
//隐藏
function hides(father,son,i){
father.hide();
father.find(son).eq(i).hide()
}
</script>
</body>
</html>