图片无法避开光标:基于jQuery实现光标触碰随机移动功能失败求助
解决图片无法躲避鼠标的问题
你的代码存在三个关键问题导致功能失效,以下是具体修正方案:
问题分析与修复要点
CSS选择器不匹配
图片使用class="som",但CSS里写的是#img(ID选择器),样式根本没作用到目标元素上,需要把选择器改成.som。缺少定位属性
要通过left和top调整元素位置,元素必须设置position: absolute或relative,否则left/top属性不会生效。这里推荐用absolute,避免元素占据原位置导致布局混乱。动画队列堆积
鼠标多次触发事件会导致动画排队执行,体验极差,需要在animate()前调用stop(true)清除之前的动画队列,确保每次只执行最新的动画。
修正后的完整代码
style.css
body { position: relative; min-height: 100vh; /* 确保body占满视口高度 */ margin: 0; /* 清除浏览器默认边距 */ } .som { position: absolute; /* 开启绝对定位,让left/top生效 */ }
index.html
<!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> <link rel="stylesheet" href="style.css"> <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script> </head> <body> <img src="https://images.pexels.com/photos/569986/pexels-photo-569986.jpeg?auto=compress&cs=tinysrgb&w=600" width="100" height="100" alt="Grey Square" class="som" /> <script> jQuery(function($) { $('.som').mouseenter(function() { var dWidth = $(document).width() - 100, // 减去图片宽度,避免超出视口 dHeight = $(document).height() - 100, // 减去图片高度 nextX = Math.floor(Math.random() * dWidth), nextY = Math.floor(Math.random() * dHeight); $(this).stop(true).animate({ left: nextX + 'px', top: nextY + 'px' }); }); }); </script> </body> </html>
额外优化说明
- 把
mouseover换成mouseenter:mouseover会在元素子节点(如果存在)触发重复事件,而mouseenter只在鼠标首次进入元素时触发一次,更适配这个场景。 - 给
body添加min-height: 100vh:确保页面高度足够,避免图片定位时出现视口高度不足的问题。
内容的提问来源于stack exchange,提问作者vikram Choudhary
相关产品推荐
相关产品推荐

