拿上一篇运行一下,感觉自己这个效果在边界处理的更好
<template> <div class="ad"> <p>vue广告悬浮</p> <img src="../assets/u=2610250996,3671218916&fm=26&gp=0.jpg" id="img" alt=""> <button @click="params()">run</button> </div> </template> <script> export default { methods:{ params(){ let count = 11 //速度 // let count = 500 //速度 let stepX = 1 let stepY = 1 let img = document.getElementById('img') let imgWidth = img.offsetWidth let imgHeight = img.offsetHeight let clientw = document.body.clientWidth; //1903(不包含滚动条) let clienth = document.body.clientHeight; //866(不包含工具条) let x = parseInt(img.getBoundingClientRect().left) let y = parseInt(img.getBoundingClientRect().top) setInterval(()=>{ let distenceX = clientw-x let distenceY = clienth-y if(distenceX-imgWidth<0||distenceX>clientw){ stepX = -stepX } if(distenceY-imgHeight<0||distenceY>clienth){ stepY = -stepY } x+=stepX y+=stepY this.changePos(img,x,y) },count) }, changePos(img,x,y){ img.style.left = x+'px' img.style.top = y+'px' } } } </script> <style lang="stylus" scoped> img position absolute left 0px top 50px width 45px height 45px </style>