首先添加广告
<div id="ad" style="left: 0;top: 0;">
<!-- 广告图片 -->
<img src="1.jpg" class="adImg">
<!-- 关闭按钮 -->
<div class="close" onclick=closeBtn()>关闭×</div>
</div>
设置广告样式
<style type="text/css">
*{
padding: 0;
margin: 0;
}
#ad{
position: absolute;
width: 300px;
position: relative;
}
.close{
position: absolute;
right: 0;
top: 0;
color: red;
line-height: 20px;
cursor: pointer;
}
.adImg{
width: 300px;
}
</style>
接下来是script部分
var ad = document.getElementById("ad"); //抓取元素
var close = document.getElementsByClassName("close");
var offsetx = 1; //每次位移的距离
var offsety =1;
接下来就是漂浮广告的核心区域
function run(){
//下面两端获取最好写在函数function里面 写在外面时会导致当你改变页面高宽时图片依旧按照原网页大小进行移动
//获得浏览器可视区域尺寸
var max_height = document.documentElement.clientHeight;
var max_width = document.documentElement.clientWidth;
//获得广告窗最大left和top
var h = max_height-ad.offsetHeight;
var w = max_width-ad.offsetWidth;
//重新赋值
var old_left = ad.style.left;
var new_left = parseInt(old_left)+offsety;
ad.style.left = new_left+'px'; //拼接
if (new_left>=w) { //判断当图片到达边界 使其反向移动
offsety=-1;
}else if(new_left<=0){
offsety = 1;
}
//同上重新赋值 只不过if判断更简单不过会有个小bug 下面会有说明
var old_top = ad.style.top;
var new_top = parseInt(old_top)+offsetx;
ad.style.top = new_top+'px';
//乘-1及每次到达边界时基于之前的方向反向移动 不过这样写有个bug 当你突然将边框移动到遮住图片的位置时图片会只有左右移动(其实有上下移动 只不过每0.02秒就继续反向了)所以最好还是像上面那样进行分别判断
if (new_top>=h||new_top<=0) {
offsetx=offsetx*(-1);
}
}
大体思路已经表明,接下来只需要加上定时器设置以及关闭按钮
var time= setInterval(run,10); //定时器
ad.onmouseover=function(){ //鼠标移入取消定时器
clearInterval(time);
}
ad.onmouseout=function(){ //鼠标移出重新设置定时器
time = setInterval(run,10);
}
function closeBtn(){ //关闭
ad.style.display="none";
}
以上就是全部代码以及思路 欢迎各路大神讨论