JS实现缓冲菜单
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{margin: 0px;padding: 0px;}
#div1{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
right: 0px;
}
</style>
<script>
window.onload = function(){
var oDiv1 = document.getElementById("div1");
//获取居中的top值
var scollTop = document.documentElement.scrollTop || document.body.scrollTop;
var windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
var iH = parseInt(scollTop + (windowHeight - oDiv1.offsetHeight) / 2);
startMove(iH);
// 滚动滑轮的时候重新计算
window.onscroll = function(){
//获取居中的top值
var scollTop = document.documentElement.scrollTop || document.body.scrollTop;
var windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
var iH = parseInt(scollTop + (windowHeight - oDiv1.offsetHeight) / 2);
startMove(iH);
}
// 改变浏览器窗口大小时重新计算
window.onresize = function(){
//获取居中的top值
var scollTop = document.documentElement.scrollTop || document.body.scrollTop;
var windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
var iH = parseInt(scollTop + (windowHeight - oDiv1.offsetHeight) / 2);
startMove(iH);
}
}
var timer = null;
function startMove(iTarget){
var oDiv1 = document.getElementById("div1");
clearInterval(timer);
timer = setInterval(function(){
//计算速度
var speed = (iTarget - oDiv1.offsetTop)/8;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
if(oDiv1.offsetTop == iTarget){
clearInterval(timer);
}else{
oDiv1.style.top = oDiv1.offsetTop + speed + 'px';
}
},30);
}
</script>
</head>
<body style = 'height: 3000px;'>
<div id = "div1"></div>
</body>
</html>
效果:
相关回顾:JS实现物体缓冲运动