随页面滚动的居中悬浮框
让目标在网页中随鼠标滚动而运动,最终停留在页面中的固定位置的效果
效果图:
代码:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
height: 3000px;
}
.box {
position: absolute;
right: 0;
width: 100px;
height: 400px;
background-color: red;
}
.close {
width: 100px;
background-color: black;
color: white;
text-align: center;
cursor: pointer;
}
</style>
</head>
<body>
<div class="box">
<div class="close">
关闭
</div>
</div>
<script>
var box = document.querySelector(".box")
var close = document.querySelector(".close")
var timer = null
function toMove(obj, speed, location) {
clearInterval(timer)
timer = setInterval(function () {
if (obj.offsetTop == location) {
speed0 = 0
clearInterval(timer)
} else {
if (location - obj.offsetTop > 0) {
speed0 = Math.ceil(speed * (location - obj.offsetTop) / 100)
//如果大于0用ceil,小于0用floor,保证speed0不会在到达之前变为0
} else {
speed0 = Math.floor(speed * (location - obj.offsetTop) / 100)
}
obj.style.top = obj.offsetTop + speed0 + "px"
}
}, 30)
}
function scrollright() {
var location = document.documentElement.scrollTop + (document.documentElement.clientHeight - box.offsetHeight) / 2
//页面滚动的距离+可视区的高度-本身的高度 除以2
location = parseInt(location) //取整防止出现小数
toMove(box, 15, location) //输入合适的速度达到效果
}
scrollright() //先调用一次让鼠标没滚动时也让box居中
document.addEventListener("scroll", function () {
scrollright()
})
close.addEventListener("click", function () {
box.style.display = "none"
})
</script>
</body>
</html>
重点是box的移动的目标距离=页面滚动的距离+可视区的高度-本身的高度 除以2
每次移动的距离speed0 = Math.ceil(speed * (location - obj.offsetTop) / 100)
或speed0 = Math.floor(speed * (location - obj.offsetTop) / 100)
离目标位置越近速度越慢 达到一个缓冲效果
if (obj.offsetTop == location) { speed0 = 0 clearInterval(timer) }
判断目标到达指定位置之后停止计时器