1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > js实现上下滑动侧边栏

js实现上下滑动侧边栏

时间:2018-11-20 10:24:46

相关推荐

js实现上下滑动侧边栏

给一个原先的电子商务网站做修改,客户说想将原先上下滑动侧边栏改的更加人性化,希望将原先匀速滑动的侧边栏改成变速运动的侧边栏,在到达目的地之前速度越变越慢。

原先一开始的时候,,这个图片是硬生生地到达可视区的中点,看得有点愣愣傻傻的。

原先的代码是这样:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="/1999/xhtml"><head><style>#testDiv1 {width:225px;height:97px;position:absolute; right:0}</style><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>上下滑动侧边栏</title><script type="text/javascript">window.onload = window.onscroll = function () {var sDiv = document.getElementById('testDiv1');// document.body.scrollTop 兼容谷歌浏览器// document.documentElement.scrollTop 兼容IE浏览器//滚动点离浏览器顶部的距离var varTop = document.documentElement.scrollTop || document.body.scrollTop;//给DIV的高赋值 sDiv.style.top = varTop + (document.documentElement.clientHeight - sDiv.offsetHeight) / 2 + 'px';}</script></head><body style="height:2000px;"><div id="testDiv1"><img src="kf.jpg" alt="" /></div></body></html>

只是让div立马居中。

要让div在到达终点前,变速地运动到终点,而且速度越来越慢,就得让sDiv.style.top的值的变化率一点一点地变慢。

于是增加了代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="/1999/xhtml"><head><style>#testDiv1 {width:225px;height:97px;position:absolute; right:0}</style><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>上下滑动侧边栏</title><script type="text/javascript">window.onload = window.onscroll = function () {var sDiv = document.getElementById('testDiv1');// document.body.scrollTop 兼容谷歌浏览器// document.documentElement.scrollTop 兼容IE浏览器//滚动点离浏览器顶部的距离var varTop=document.documentElement.scrollTop||document.body.scrollTop;//oDiv.style.top=scrollTop+(document.documentElement.clientHeight-oDiv.offsetHeight)/2+'px';var t = varTop + (document.documentElement.clientHeight - sDiv.offsetHeight) / 2;//给DIV的高赋值//document.documentElement.clientHeight可见区域的高度 //oDiv.style.top=scrollTop+(document.documentElement.clientHeight-oDiv.offsetHeight)/2+'px';//让速度发生变化 startMove(parseInt(t),7);}var varTimer = null;function startMove(destination,speed) {var sDiv = document.getElementById('testDiv1');//开启一个定时器 clearInterval(varTimer);varTimer = setInterval(function () {//div一开始离目标的距离除以speed div移动的速度 div距离越近 速度越小var varSpeed = (destination - sDiv.offsetTop) / speed;//Round是四舍五入 ceil向上取整。。floor向下取整 varSpeed = varSpeed > 0 ? Math.ceil(varSpeed) : Math.floor(varSpeed);//到达目的地 清除定时器if (sDiv.offsetTop == destination) {clearInterval(varTimer);}else {//移动 sDiv.style.top = sDiv.offsetTop + varSpeed + 'px';}}, 30);}</script></head><body style="height:3000px;"><div id="testDiv1"><img src="kf.jpg" alt="" /></div></body></html>

View Code

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。