Jquery .mouseover()不工作(抓我)

Jquery .mouseover() not working (catch me)

本文关键字:抓我 工作 Jquery mouseover      更新时间:2023-09-26

我正在做功课,我试图添加更多的鼠标悬停,但它不工作

$("button").mouseover(function() {
  $(this).css({
    left: (Math.random() * 300) + "px",
    top: (Math.random() * 300) + "px",
  }, 1);
});
button {
  position: absolute;
  top: 400px;
  left: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <h1>Catch me if you can !</h1> 
  <div class="main"></div>
  <button>
    <img src="cat/grey-cat-001.gif">
  </button>
</body>

这是因为每个元素的默认position都是static,这不会对top, left, rightbottom样式产生任何影响。

HTML元素默认定位为静态。

静态定位元素不受top, bottom, left和right属性的影响。

所以你只需要为按钮添加position: relativeposition: absolute,就像下面的代码片段:

$("button").mouseover(function() {
  $(this).css({
    left: (Math.random() * 300) + "px",
    top: (Math.random() * 300) + "px",
  }, 1);
});
button {
  position: relative;  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<body>
  <div class="main"></div>
  <button>
    <img src="cat/grey-cat-001.gif">
  </button>
</body>