jQuery-笔记 案例: 电梯导航
实现的功能点
- 页面到today盒子 电梯导航就会出现
- 点击 电梯导航LI 计算出页面要去到的位置
- 滚动到 电梯导航 相应的内容区域 相对应的导航栏目会添加 .current
ul,li,div,p,body{
margin:0;padding:0;}.box{
width:800px;margin:auto;}.bigbox{
width:100%;height:1000px;background-color:#eee;}.today{
width:100%;height:100px;background-color:#999;}.box1,.box2,.box3,.box4{
width:100%;height:800px;background-color:#ccc;margin:10px 0;}.fixedtool{
position:fixed;left:10px;top:50%;width:80px;}.fixedtool ul li{
line-height:25px;list-style:none;text-align:center;}.fixedtool ul li:hover,.current{
background-color:red;color:#fff;}
html框架
<div class="box">
<div class="bigbox"></div>
<div class="today"></div>
<div class="box1 in">家用电器</div>
<div class="box2 in ">手机通读</div>
<div class="box3 in">电脑办公</div>
<div class="box4 in">精品家具</div>
</div>
<div class="fixedtool">
<ul>
<li class="current">家用电器</li>
<li>手机通读</li>
<li>电脑办公</li>
<li>精品家具</li>
</ul>
</div>
jQuery 代码写法
$(function() {
// 当我们点击 li 此时不需执行页面滚动事件里的LI的背景选择 添加 .current 可以用节流阀来解决
var flag = true; //节流阀 互斥锁
// 到today盒子 电梯导航就会出现
var ftop = $(".today").offset().top;
floortool();
function floortool() {
if ($(document).scrollTop() >= ftop) {
$(".fixedtool").fadeIn();
} else {
$(".fixedtool").fadeOut();
}
}
$(window).scroll(function() {
floortool();
// 滚动到 电梯导航 相应的内容区域 相对应的导航栏目会添加 .current
if (flag) {
$(".box .in").each(function(i, ele) {
if ($(document).scrollTop() >= $(ele).offset().top) {
$(".fixedtool li").eq(i).addClass("current").siblings().removeClass("current");
}
})
}
})
// 点击 电梯导航 滚动动一相应的内容区域
$(".fixedtool li").click(function() {
flag = false;
// 点击 LI 计算出页面要去往的位置
// 选对应的索引号的内容区盒子, 计算卷去的顶部距离
var current = $(".box .in").eq($(this).index()).offset().top;
$("body,html").animate({
scrollTop: current
}, function() {
flag = true;
});
//
$(this).addClass("current").siblings().removeClass("current");
})
})
