实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> #box{width:100px;height:100px;background:pink;position:absolute;} </style> </head> <body> <!-- <div id="box" style="left:0px;top:0px;"></div> --> <img src="./3.jpg" alt="" style="left:0px;top:0px;" id="box"> </body> <script> var box = document.getElementById('box'); var x = 10; var y = 10; setInterval(function(){ //控制div碰到横向的边界地方进行反向移动 if(parseInt(box.style.left)>= (window.innerWidth-100) ){ x = -x; } if(parseInt(box.style.left)<0){ x = -x; } //控制div碰到纵向的边界的地方进行反向移动 if(parseInt(box.style.top)>= (window.innerHeight-100) ){ y = -y; } if(parseInt(box.style.top)<0){ y = -y; } //让我们的div开始移动 box.style.left = parseInt(box.style.left)+x+'px'; box.style.top = parseInt(box.style.top) +y+'px'; },100) </script> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例