单击鼠标并更新T F时图像消失

问题描述 投票:0回答:1

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

我正试图用鼠标移动图像并记录鼠标位置。当我点击我希望图像停止跟随鼠标。 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>
javascript jquery
1个回答
0
投票
  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>
© www.soinside.com 2019 - 2024. All rights reserved.