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

时间:2018-04-17 17:45:40

标签: javascript onclick mouseevent

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。

很有帮助。

2 个答案:

答案 0 :(得分:0)

您的按钮需要激活鼠标移动监听器,以便跟踪鼠标移动的任何内容,可能是public class OrderedProduct { public Guid Id { get; set; } //other public Guid ShipmentId { get; set; } public Shipment other { get; set; }//Change } document。除此之外,你很亲密。我使用内联样式,但显然单独的css文档在这个狭窄的例子之外更好。



window

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 = "";
}




答案 1 :(得分:0)

你可以这样做。

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;
  }
});