我需要用户单击并按住并移动鼠标时才能向左或向右移动div,其中div的位置将与按下时的x位置相等。我知道这个问题以前已经回答过,但似乎无法解决。我使用的是简化版本,因此在控制台中仅显示“ hello”,而不是移动div。任何帮助将不胜感激。
var divEl = document.getElementById("div");
var down = false;
divEl.addEventListener('mousedown', function (event) {
var down = true;
console.log("true");
}, true);
window.addEventListener('mouseup', function (event) {
var down = false;
console.log("false");
}, true);
document.addEventListener('mousemove', function(event) {
event.preventDefault();
if (down) {
console.log("hello");
}
}, true);
当我单击div时,将获得“ true”控制台日志,而当释放鼠标时,将获得“ false”控制台日志。但是我无法获取“ hello”控制台日志。
答案 0 :(得分:2)
您在回调函数中创建了新变量。删除var
,它会起作用:
var divEl = document.getElementById("div");
var down = false;
divEl.addEventListener('mousedown', function (event) {
down = true;
console.log("true");
}, true);
window.addEventListener('mouseup', function (event) {
down = false;
console.log("false");
}, true);
document.addEventListener('mousemove', function(event) {
event.preventDefault();
if (down) {
console.log("hello");
}
}, true);
通过此链接var statement at MDN
详细了解范围答案 1 :(得分:0)
我认为您正在寻找类似的东西
var mousePosition;
var offset = [0,0];
var div;
var isDown = false;
div = document.createElement("div");
div.style.position = "absolute";
div.style.left = "0px";
div.style.top = "0px";
div.style.width = "100px";
div.style.height = "100px";
div.style.background = "red";
div.style.color = "blue";
document.body.appendChild(div);
div.addEventListener('mousedown', function(e) {
isDown = true;
offset = [
div.offsetLeft - e.clientX,
div.offsetTop - e.clientY
];
}, true);
document.addEventListener('mouseup', function() {
isDown = false;
}, true);
document.addEventListener('mousemove', function(event) {
event.preventDefault();
if (isDown) {
mousePosition = {
x : event.clientX,
y : event.clientY
};
div.style.left = (mousePosition.x + offset[0]) + 'px';
div.style.top = (mousePosition.y + offset[1]) + 'px';
}
}, true);