我有两个问题。我想要移动的图像消失,鼠标点击的状态不会更新。
我正试图用鼠标移动图像并记录鼠标位置。当我点击我希望图像停止跟随鼠标。 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>
$("#gallery").html("The image is at: " + xPos + ", " + yPos);
覆盖它。您需要将坐标写入其他元素。follow
函数传递给click
处理程序时,你从其原始范围中采集,因此它不再看到init
,(2)你取消订阅mousemove
事件所以该功能不再运行。所以你需要将$("#clickstatus").html("Image is following mouse T/F" + ": " + !init);
移动到click
处理程序。css
函数。此外,不需要包装$(document).mousemove(function(e) {
。left
和top
属性有任何影响,元素应该将position
设置为fixed
或absolute
。$(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>