我有两个问题。我要移动的图像消失了,鼠标单击的状态没有更新。
我正在尝试用鼠标移动图像并记录鼠标的位置。当我单击时,我希望图像停止跟随鼠标。暂存位置将停止计数,并且跟随鼠标的鼠标图像将显示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>
答案 0 :(得分:0)
$("#gallery").html("The image is at: " + xPos + ", " + yPos);
覆盖了它。您需要将坐标写入其他元素。follow
函数传递给您从其原始作用域中拔出的click
处理程序时,它看不到{{ 1}},(2)您取消了init
事件的订阅,因此该函数不再运行。因此,您需要将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. */
}