首页 > 解决方案 > 鼠标单击和 TF 更新时图像消失

问题描述

我有两个问题。我要移动的图像消失了,鼠标点击的状态没有更新。

我正在尝试用鼠标移动图像并记录鼠标位置。当我单击时,我希望图像停止跟随鼠标。souse 位置将停止计数,鼠标图像跟随鼠标将显示为 false。

$(document).ready(function() {
  var init = true;
  $(document).on('click', function() {
    $(this)[init ? 'on' : 'off']('mousemove', follow);
    init = !init;
  });

  function follow(e) {
    var xPos = e.pageX;
    var yPos = e.pageY;
    $("#gallery").html("The image is at: " + xPos + ", " + yPos);
    $("#clickstatus").html("Image is following mouse T/F" + ": " + !init);
    $(document).mousemove(function(e) {
      $("#moveimage").mousemove({
        left: e.pageX,
        top: e.pageY
      });
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>IT 411</h1>
<h2>Displaying a gallery of images</h2>
<hr />
<p>Click anywhere on this page to make the image move using mousemove</P>
<p id="clickstatus"></p>
</div>

<div id="gallery">
  <img id="moveimage" class="image" src="images/gnu.jpg" height="200px" width="250px" />
</div>

标签: javascriptjquery

解决方案


  1. 图像消失,因为您用 覆盖它$("#gallery").html("The image is at: " + xPos + ", " + yPos);。您需要将坐标写入其他元素。
  2. 鼠标单击的状态没有更新有两个原因:(1)当您将follow函数传递给click处理程序时,您从其原始范围中提取,因此它不再看到init,(2)您取消订阅mousemove事件,因此函数不会再跑。所以你需要移动$("#clickstatus").html("Image is following mouse T/F" + ": " + !init);click处理程序。
  3. 要更改图像的坐标,您需要使用 jQuery 的css函数。$(document).mousemove(function(e) {也不需要包装。
  4. 要使lefttop属性具有任何效果,该元素position必须设置为fixedabsolute

$(document).ready(function() {
  var init = true;
  $(document).on('click', function() {
    $(this)[init ? 'on' : 'off']('mousemove', follow);
    init = !init;
    // 2.
    $("#clickstatus").html("Image is following mouse T/F" + ": " + !init);
  });

  function follow(e) {
    var xPos = e.pageX;
    var yPos = e.pageY;
    $("#coordinates").html("The image is at: " + xPos + ", " + yPos);
    // 3.
    $("#moveimage").css({
      left: e.pageX,
      top: e.pageY
    });
  }
});
#moveimage{
  position: fixed; /* 4. */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>IT 411</h1>
<h2>Displaying a gallery of images</h2>
<hr />
<p>Click anywhere on this page to make the image move using mousemove</P>
<p id="clickstatus"></p>
</div>

<div id="gallery">
  <img id="moveimage" class="image" src="images/gnu.jpg" height="200px" width="250px" />
</div>
<!-- 1. -->
<div id="coordinates"></div>


推荐阅读