js之漂浮广告效果
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> #box{width:150px;height:200px;background:url(pic.jpg) no-repeat; position:absolute;left:0;top:0;} </style> <script type="text/javascript"> window.onload=function(){ var box=document.getElementById('box'); var close=document.getElementById('close'); //获取可是区域的高度和宽度 var win_height=document.documentElement.clientHeight; var win_width=document.documentElement.clientWidth; //计算元素可到达最大的高度和宽度 var max_top=win_height-box.offsetHeight; var max_left=win_width-box.offsetWidth; var x=1;y=1; console.log(max_top); //设置定时器调用的函数 function run(){ //格式不要写错 //获取旧的top和left var old_left=box.offsetLeft; var old_top=box.offsetTop; //计算新的top和left var new_left=old_left+x; var new_top=old_top+y; //将新值赋值回去 box.style.left=new_left+'px'; box.style.top=new_top+'px'; if(new_top==max_top){ y=-1; } if(new_top==0){ y=1; } if(new_left==max_left){ x=-1; } if(new_left==0){ x=1; } } //函数结束 //设置全局定时器 var timer=setInterval(run,40); //40毫秒走一次 box.onmouseover=function(){ clearInterval(timer);//鼠标移入,停止定时器 } box.onmouseout=function(){ //恢复定时器 timer=setInterval(run,40); } close.onclick=function(){ box.style.display='none'; //点击关闭安装,隐藏广告 } } </script> </head> <body> <div id="box"> <img src="shut.jpg" id="close"/> </div> </body> </html>