JavaScript学习笔记-随滚轮匀速滑动的浮动广告窗动画

时间:2020-12-23 10:46:07
 <!DOCTYPE html>

 <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
* { padding: 0; margin: 0; border: 0; }
.adv { position: relative; width: 150px; height: 300px; z-index: 1; top: 120px; left: 20px; }
.con, .close1 { position: absolute; }
.con { width: 150px; height: 300px; top: 0; left: 0; background-color: #7ca1ee; }
.close1 { width: 23px; height: 23px; font-size: 22px; text-align: center; color: #ffffff; top: 5px; left: 120px; z-index: 999; }
.close1:hover { background-color: #808080; }
.text { height: 20000px; width: 200000px; margin: 0 auto; }
</style>
</head>
<body> <div class="adv" id="advC">
<div class="con"></div>
<div class="close1" onclick="clo()">×</div>
</div>
<div class="text"> 唯一的缺点就是横向滑动效果不好,建议还是用固定式,不需要滑动比较好 </div> <script type="text/javascript">
var adv = document.getElementById("advC");//获取广告窗口 function clo() {//关闭广告窗口函数
adv.style.display = "none";
} var uu = null;//计时器全局变量声明 function scol() {
clearInterval(uu);//清除计时器 //获取广告即将随滚动条滑动到的坐标
var advTopX = 120 + parseInt(document.body.scrollTop);
var advLeftX = 20 + parseInt(document.body.scrollLeft); var advTop, advLeft;//获取广告当前坐标
if (adv.currentStyle) {
advTop = parseInt(adv.currentStyle.top);
advLeft = parseInt(adv.currentStyle.left);
} else {
advTop = parseInt(document.defaultView.getComputedStyle(adv, null).top);
advLeft = parseInt(document.defaultView.getComputedStyle(adv, null).left);
} //计算从当前坐标 到 即将滑动到的坐标 需要跑多少距离
var TopLong = advTopX - advTop;
var LeftLong = advLeftX - advLeft; //利用计时器实现广告匀速随滚动条滑动效果
uu = setInterval(function () {
if ((advTop - 10 < advTopX && advTop + 10 > advTopX) && (advLeft - 10 < advLeftX && advLeft + 10 > advLeftX)) {//判断垂直与横向是否处于该区间值,前后误差10px
adv.style.top = advTopX + "px";//垂直距离=即将滑动到的距离
adv.style.left = advLeftX + "px";//横向距离=即将滑动到的距离
clearInterval(uu);//清除计时器,即到这里的时候就跳出计时器,固定广告位置 } else {
advTop += parseFloat(TopLong / 200);//将需要滑动的距离平均分为200份
adv.style.top = Math.ceil(advTop) + "px";//每次计时器进来滑动1份 advLeft += parseFloat(LeftLong / 200);//将需要滑动的距离平均分为200份
adv.style.left = Math.ceil(advLeft) + "px";//每次计时器进来滑动1份
//这里的份数可以调节滑动速度的快慢,但是必须为整十整百整千,数字越大越慢,越小越快
}
}, 1); } window.onscroll = scol;//注册滚轮滑动事件 </script>
</body>
</html>