原理
每個盒子的索引值和每個按鈕的索引一一對應,然後運動到相對應的盒子上 也就是scrollTop的值
成果圖
<style>
.box2 {
position: relative;
width: 600px;
height: 500px;
background-color: pink;
}
.box3 {
position: relative;
width: 600px;
height: 500px;
background-color: rebeccapurple;
}
.box4 {
position: relative;
width: 600px;
height: 500px;
background-color: gold;
}
.box5 {
position: relative;
width: 600px;
height: 500px;
background-color: red;
}
.go {
background-color: gray;
display: none;
position: fixed;
right: 10px;
bottom: 100px;
}
button {
display: block;
}
</style>
-----------------------------------------------------
<div class="con">
<div class="box2">手機區域</div>
<div class="box3">電腦區域</div>
<div class="box4">電視區域</div>
<div class="box5">冰箱區域</div>
</div>
<div class="go">
<button>back手機區域</button>
<button>back電腦區域</button>
<button>back電視區域</button>
<button>back冰箱區域</button>
</div>
---------------------------------------------
<script>
$(function() {
//刷新之後回到頂部
$('html,body').stop().animate({
scrollTop: 0
})
//固定欄的顯示隱藏
var box3Top = $('.box3').offset().top;
$(window).scroll(function() {
if ($(document).scrollTop() >= box3Top) {
$('.go').fadeIn();
} else {
$('.go').fadeOut();
}
})
})
// 電梯效果
//點擊按鈕,就跳到對應的div
$('.go button').click(function() {
//獲取相對應的div到頂部的距離
var boxTop = $('.con div').eq($(this).index()).offset().top;
//跳到對應的div
$('html,body').stop().animate({
scrollTop: boxTop
})
})
</script>