<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style type="text/css"> * { padding: 0; margin: 0; } #box { width: 500px; position: relative; margin: auto; } .close { position: absolute; color: #000; right: 0; top: 0; cursor: pointer; } .img { width: 500px; } </style> </head> <body> <div id="box" style="left: 0;top: 0;"> <!-- 广告图片 --> <img src="../assest/images/background.jpeg" class="img"> <!-- 关闭按钮 --> <div class="close" onclick=closeBtn()>关闭×</div> </div> </body> <script> () => { //获得浏览器可视区域 var height = document.documentElement.clientHeight; var width = document.documentElement.clientWidth; //获得广告窗最大left和top var height = height - box.offsetHeight; var width = width - box.offsetWidth; var left = box.style.left; var new_left = parseInt(eft) + offsety; box.style.left = new_left + 'px'; //判断当图片的边界 if (new_left >= width) { offsety = -1; } else if (new_left <= 0) { offsety = 1; } //重新赋值 var top = box.style.top; var new_top = parseInt(top) + offsetx; box.style.top = new_top + 'px'; if (new_top >= h || new_top <= 0) { offsetx = offsetx * (-1); } } //关闭按钮 const closeBtn = () => { box.style.display = "none"; } </script> </html>