javascript - 鼠标单击和 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>
解决方案
- 图像消失,因为您用 覆盖它
$("#gallery").html("The image is at: " + xPos + ", " + yPos);
。您需要将坐标写入其他元素。 - 鼠标单击的状态没有更新有两个原因:(1)当您将
follow
函数传递给click
处理程序时,您从其原始范围中提取,因此它不再看到init
,(2)您取消订阅mousemove
事件,因此函数不会再跑。所以你需要移动$("#clickstatus").html("Image is following mouse T/F" + ": " + !init);
到click
处理程序。 - 要更改图像的坐标,您需要使用 jQuery 的
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>
推荐阅读
- nginx - 如何使用 nginx 代理远程服务器?
- javascript - 将文本框上的输入相乘并在警报上显示答案(javascript)
- python-2.7 - tensorflow 错误:InvalidArgumentError:元组组件 1 中的形状不匹配。预期 [1],得到 [5]
- python - 通过多列运行需要多个参数的函数 - Pandas
- python - Python 2 csv.DictWriter() Unicode 编码异常处理
- python - Tensorflow conv2d_transpose:out_backprop 的大小与计算的不匹配
- angularjs - Ionic (Angularjs) 和 Devextreme Datagrid 的集成,无法显示来自 $http JSON 的数据
- python - Google 已停用 QPX Express API
- regex - 正则表达式查找 URL,包括仅以 //(协议相关 URL)开头的 URL
- reactjs - 反应 setstate 不重新调整