单击按钮时使 div 跟随光标,单击(另一个)按钮时停止跟随光标并返回到起始位置

Make div follow cursor on button click, and stop following cursor and go back to starting position on (another) button click

var bx = document.getElementById("movingbox");
var takeMeBtn = document.getElementById('takeMeBtn');
var letGoBtn = document.getElementById('letGoBtn');

function mouseMov(e) {
    bx.style.left = -50 + e.clientX + "px";
    bx.style.top = -50 + e.clientY + "px";
    bx.style.zIndex = -99;
}

takeMeBtn.clickToggle = function fn(e) {
    bx.style.left = -50 + e.clientX + "px";
    bx.style.top = -50 + e.clientY + "px";
    bx.style.zIndex = -99;
}


letGoBtn.onclick = function() {
    bx.style.position = "fixed";
    bx.style.top = 50;
    bx.style.left = 50;
}

大家好!

当我单击按钮 "takeMeBtn" 时,我一直在尝试让 "movingbox" 移动并跟随光标位置。

但是,当点击 "takeMeBtn" 时,它只会把自己放在光标的当前位置,然后停留在那里。

我也想让它回到它的起始位置,或者任何位置,当我点击 "letGoBtn",但我想我可以自己管理那个。

我不想为此使用 jQuery。

非常感谢任何帮助。

你的按钮需要激活一个 mousemove 侦听器,用于任何你想跟踪鼠标经过的地方,可能是 documentwindow。除此之外,你很接近。我使用了内联样式,但显然在这个狭窄的示例之外使用单独的 css 文档更好。

var bx = document.getElementById("movingbox");
var takeMeBtn = document.getElementById('takeMeBtn');
var letGoBtn = document.getElementById('letGoBtn');

function mouseMov(e) {
    bx.style.left = -50 + e.clientX + "px";
    bx.style.top = -50 + e.clientY + "px";
}

takeMeBtn.onclick = function(e) {
  document.addEventListener('mousemove', mouseMov)
}


letGoBtn.onclick = function() {
    document.removeEventListener('mousemove', mouseMov)
    bx.style.top = "";
    bx.style.left = "";
}
<button id="takeMeBtn">click</button>
<button id="letGoBtn">unclick</button>
<div id="movingbox" style="width:30px; height:30px; border: 1px solid black; position:absolute;"></div>

你可以这样做。

HTML:

<button id="takeMeBtn">take me</button>
<button id="letGoBtn">let go</button>
<div id="movingbox"></div>

var bx = document.getElementById("movingbox");
var takeMeBtn = document.getElementById('takeMeBtn');
var letGoBtn = document.getElementById('letGoBtn');

CSS

div {
    width: 50px;
    height: 50px;
    background: red;
    position: absolute;
}

JS

// flag: div should/not move
let move = false;

// switch flag
takeMeBtn.addEventListener('click', event => {
  move = true;
});

// reset flag and position
letGoBtn.addEventListener('click', event => {
  move = false;
  bx.style.top = 0;
  bx.style.left = 0;
  bx.style.zIndex = 0;
});

// change its position on each mousemove event if the flag is set to true
document.addEventListener('mousemove', event => {
  if (move === true) {
    bx.style.top = event.clientY + 'px';
    bx.style.left = event.clientX + 'px';
    bx.style.zIndex = -99;
  }
});