鼠标点到左边的哪种颜色的小矩形,自动滚动到哪一部分。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>页面滚动</title>
<style>
body{
margin:0;
}
#page1{
background:red;
}
#page2{
background: orange;
}
#page3{
background:green;
}
#page4{
background:cyan;
}
#page5{
background:purple;
}
.icon-bar{
position: fixed;
left:10px;
top:300px;
100px;
border:2px solid #fff;
list-style:none;
margin:0;
padding:0;
}
.icon-bar li{
height:30px;
cursor:pointer;
}
</style>
</head>
<body>
<div class="scroll-page">
<div id="page1"></div>
<div id="page2"></div>
<div id="page3"></div>
<div id="page4"></div>
<div id="page5"></div>
</div>
<ul class="icon-bar">
<li style="background:red"></li>
<li style="background:orange"></li>
<li style="background:green"></li>
<li style="background:cyan"></li>
<li style="background:purple"></li>
</ul>
<script>
//获取页面高度
var pageHeight = window.innerHeight || document.documentElement.offsetHeight;
var divs = document.querySelectorAll(".scroll-page div");
for (var i = 0; i < divs.length; i ++) {
divs[i].style.height = pageHeight + "px";
}
//获取所有按钮
var ions = document.querySelectorAll(".icon-bar li");
for (var i = 0; i < ions.length; i ++) {
ions[i].index = i;
ions[i].onclick = function(){
//目标scrollTop值
var distTop = pageHeight * this.index;
animateScroll(distTop, 1000);
}
}
function animateScroll(distTop, duration) {
var startTime = createTime(); //开始时间
var currentTop = document.body.scrollTop; //当前的值
var timer = setInterval(run, 13);
function run(){
var temp = Math.min(createTime() - startTime, duration);
var percent = temp / duration;
if (percent === 1) {
clearInterval(timer);
}
//变化
document.body.scrollTop = currentTop + (distTop - currentTop) * percent;
}
function createTime(){
return (+ new Date);
}
}
</script>
</body>
</html>