gpt4 book ai didi

javascript - JavaScript 中的鼠标事件问题

转载 作者:行者123 更新时间:2023-11-30 05:34:36 25 4
gpt4 key购买 nike

我刚开始学习 JavaScript,我正在尝试创建一个执行以下步骤的函数。

  1. 记录用户点击并按住的位置的 x 坐标(onmousedown(?),而不是 onclick)。
  2. 然后,当鼠标仍被按下时,鼠标在 x 方向上每移动 ±100 个单位,我希望发生一个 Action (对于这个问题不重要,但例如,会出现一个弹出窗口)。
  3. 当用户释放鼠标时 (onmouseup(?)),该函数停止跟踪用户的鼠标位置并且操作停止(如果如示例所示,弹出窗口将不再弹出)
  4. 如果用户再次点击,请重复步骤 1-3。

这是我悲惨的尝试......

<DOCTYPE! html>
<html >
<body onmousedown="doThing()">
<script type="text/javascript">

//global variable that tracks whether or not mouse is down or up.
var mouseDown = 0;

document.body.onmousedown = function()
{
++mouseDown;
}
document.body.onmouseup = function()
{
--mouseDown;
}

//displays the state of the mouse on screen. 1 means mouse is down, 0 means mouse is up.
function track()
{
mouseState.innerHTML = mouseDown;
}

//when the mouse moves 100 units in either direction from the location of the initial downclick, a popup appears
function doThing()
{
var xPos = window.event.clientX;
if (mouseDown==1 && ((Math.abs(xPos-window.event.clientX))>100))
alert("yay");

}

</script>
<div align="center"><span id="mouseState"></span></div>
</body>
</html>

非常感谢任何关于任何事情的反馈/帮助/提示!

最佳答案

这就是我想出的:JSFiddle

//global variable that tracks whether or not mouse is down or up.
var mouseDown = 0;
//global variable that tracks where the mouse position when pressed
var firstPos = 0;
document.body.onmousedown = function(event)
{
mouseDown = 1;
track();
firstPos = window.event.clientX;
}
document.body.onmouseup = function(event)
{
mouseDown = 0
track();
firstPos = 0;
}
document.body.onmousemove = function()
{
if (mouseDown == 1){
doThing();
}
}
document.body.onmouseout = function()
{
//important because when you click the alert button `onmouseup` won't be triggered
mouseDown = 0;
}
//displays the state of the mouse on screen. 1 means mouse is down, 0 means mouse is up.
function track()
{
mouseState.innerHTML = mouseDown;
}

//when the mouse moves 100 units in either direction from the location of the initial downclick, a popup appears
function doThing(event)
{
if (mouseDown==1 && ((Math.abs(firstPos-window.event.clientX))>100))
alert("yay");

}

关于javascript - JavaScript 中的鼠标事件问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24729616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com