效果图
添加了一个解决兼容性问题的求滚动长度距离的函数
/**
* 获取滚动的头部距离和左边距离
* scroll().top scroll().left
* @returns {{top: number, left: number}}
*/
function scroll() {
if(window.pageXOffset!==null)//新型模式
{
return {
top:window.pageYOffset,
left:window.pageXOffset
}
}else if(document.compatMode==="CSS1Compat"){//严格模式
return{
top:document.documentElement.scrollTop,
left:document.documentElement.scrollLeft,
}
}
return{//异常模式
top:document.body.scrollTop,
left:document.body.scrollLeft,
}
}
HTML
<div id="side">
<img src="图片/6.jpg" alt="">
</div>
还有一坨的p为了弄长点好滚动
css
*{
margin: 0;
padding: 0;
list-style: none;
border: none;
}
#side{
width: 150px;
height: 200px;
position: absolute; 默认对body定位
left: 0;
top: 150px;
}
#side img{
width: 100%;
height: 100%;
}
p{
height: 50px;
text-align: center;
font-size: 20px;
}
JS
分析
网页滚动(onscroll)时,侧边广告会缓动(缓动动画)滑到最初的位置
缓动动画:缓动系数、定时器
定时器:先清除后设置、在达到要求之后,及时清除定时器
<script>
function $(id) {
return document.getElementById(id);
}
window.onload = function () {
console.log($("side"));
var Offsettop=$("side").offsetTop;//获取侧边广告距离顶部的距离
//2、窗口滚动
var begin=0,end=0,timer=null;
window.onscroll = function () {
//2、0在时间开始的地方清除
clearInterval(timer);
//2、1获取滚动高度
var scrollTop=scroll().top;
Ed=offsettop+scrollTop;
//结束位置为:滚动的长度和当前距离页面顶部的长度
timer=setInterval(function () {
begin=begin+(Ed-begin)*0.2;
//根据公式,设置起止值
$("side").style.top=begin+"px";
//begin
if(Math.round(begin)===end){
//定时器使用了要清除
clearInterval(timer);
}
},20);
}
}