好吧,看起来应该很简单。我需要取一个已经存在的div并根据窗口内的鼠标位置移动它。我到处搜索过,它让我采用过于复杂的方式做同样的事情,并涉及使用j-query。我需要严格使用javascript来实现我的目标。
方法:
var mousePosition;
var div;
(function createDiv(){
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";
div.addEventListener('mousedown', handleKeyPressed, true);
document.body.appendChild(div);
})();
function handleKeyPressed(event) {
event.preventDefault();
mousePosition = {
x : event.clientX,
y : event.clientY
};
div.style.left = mousePosition.x;
div.style.top = mousePosition.y;
//alert("whoa!");
}
答案 0 :(得分:36)
我认为你正在寻找更像这样的东西
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);
答案 1 :(得分:6)
检查这是否比adeneo更顺畅:FIDDLE
var m = document.getElementById('move');
m.addEventListener('mousedown', mouseDown, false);
window.addEventListener('mouseup', mouseUp, false);
function mouseUp() {
window.removeEventListener('mousemove', move, true);
}
function mouseDown(e) {
window.addEventListener('mousemove', move, true);
}
function move(e) {
m.style.top = e.clientY + 'px';
m.style.left = e.clientX + 'px';
};
答案 2 :(得分:5)
所有其他答案(包括已接受的答案)不适用于触摸输入。 触摸输入的事件不同于鼠标输入的事件。请参见Using Touch Events(关于MDN)。
以下代码段也适用于触摸输入。我突出显示了需要添加以支持触摸设备的所有代码行。
这里的基本思想是,类列表中包含draggable
的每个元素都应可拖动。当您需要拖动大量元素时,更容易遵循此概念。
有关示例,请参见this小故障页面和后续内容。
const d = document.getElementsByClassName("draggable");
for (let i = 0; i < d.length; i++) {
d[i].style.position = "relative";
}
function filter(e) {
let target = e.target;
if (!target.classList.contains("draggable")) {
return;
}
target.moving = true;
//NOTICE THIS ?
e.clientX ?
(target.oldX = e.clientX,
target.oldY = e.clientY) :
(target.oldX = e.touches[0].clientX,
target.oldY = e.touches[0].clientY)
//NOTICE THIS ? Since there can be multiple touches, you need to mention which touch to look for, we are using the first touch only in this case
target.oldLeft = window.getComputedStyle(target).getPropertyValue('left').split('px')[0] * 1;
target.oldTop = window.getComputedStyle(target).getPropertyValue('top').split('px')[0] * 1;
document.onmousemove = dr;
//NOTICE THIS ?
document.addEventListener('touchmove', dr, {passive: false})
//NOTICE THIS ?
function dr(event) {
event.preventDefault();
if (!target.moving) {
return;
}
//NOTICE THIS ?
event.clientX ?
(target.distX = event.clientX - target.oldX,
target.distY = event.clientY - target.oldY) :
(target.distX = event.touches[0].clientX - target.oldX,
target.distY = event.touches[0].clientY - target.oldY)
//NOTICE THIS ?
target.style.left = target.oldLeft + target.distX + "px";
target.style.top = target.oldTop + target.distY + "px";
}
function endDrag() {
target.moving = false;
}
target.onmouseup = endDrag;
//NOTICE THIS ?
target.ontouchend = endDrag;
//NOTICE THIS ?
}
document.onmousedown = filter;
//NOTICE THIS ?
document.ontouchstart = filter;
//NOTICE THIS ?
.draggable {
width: 100px;
height: 100px;
background: red;
}
<div class="draggable"></div>
答案 3 :(得分:1)
jquery更容易部署。我很惊讶你说你不想学习它。
您可以将jquery文件保存在本地计算机中,这样就不需要上网了 使用jquery功能。
在我的情况下,我已将其保存在工具文件夹中。所以我不需要上网。
对于所有js,上面回答了很多js代码行,你只需要一个小行。
<script src="/common/tools/jquery-1.10.2.js"></script>
<script src="/common/tools/jquery-ui.js"></script>
<script>
$(function() {
$( "#mydiv_to_make_draggable" ).draggable();
});
</script>
答案 4 :(得分:1)
我只是对@adeneo非常好的工作答案做了一点改动。 如果所有内容都包含在函数中,并且每个事件都附加到div,则可以将其用作库的一部分。
调用以下函数传递id。如果div不存在则会创建。
function drag_div(div_id){
var div;
div = document.getElementById(div_id);
if(div == null){
div = document.createElement("div");
div.id = div_id;
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) {
div.isDown = true;
div.offset = [
div.offsetLeft - e.clientX,
div.offsetTop - e.clientY
];
}, true);
div.addEventListener('mouseup', function() {
div.isDown = false;
}, true);
div.addEventListener('mousemove', function(event) {
event.preventDefault();
if (div.isDown) {
div.mousePosition = {
x : event.clientX,
y : event.clientY
};
div.style.left = (div.mousePosition.x + div.offset[0]) + 'px';
div.style.top = (div.mousePosition.y + div.offset[1]) + 'px';
}
}, true);
}
答案 5 :(得分:0)
您可以将此库用作库。完美运作。我在github上找到了它,但有时由于共享器将“ mouseup”放入元素而被卡住了。我将其更改为文档,并解决了该问题。这是固定版本
'use strict';
/**
* Makes an element draggable.
*
* @param {HTMLElement} element - The element.
*/
function draggable(element) {
var isMouseDown = false;
// initial mouse X and Y for `mousedown`
var mouseX;
var mouseY;
// element X and Y before and after move
var elementX = 0;
var elementY = 0;
// mouse button down over the element
element.addEventListener('mousedown', onMouseDown);
/**
* Listens to `mousedown` event.
*
* @param {Object} event - The event.
*/
function onMouseDown(event) {
mouseX = event.clientX;
mouseY = event.clientY;
isMouseDown = true;
}
// mouse button released
document.addEventListener('mouseup', onMouseUp);
/**
* Listens to `mouseup` event.
*
* @param {Object} event - The event.
*/
function onMouseUp(event) {
isMouseDown = false;
elementX = parseInt(element.style.left) || 0;
elementY = parseInt(element.style.top) || 0;
}
// need to attach to the entire document
// in order to take full width and height
// this ensures the element keeps up with the mouse
document.addEventListener('mousemove', onMouseMove);
/**
* Listens to `mousemove` event.
*
* @param {Object} event - The event.
*/
function onMouseMove(event) {
if (!isMouseDown) return;
var deltaX = event.clientX - mouseX;
var deltaY = event.clientY - mouseY;
element.style.left = elementX + deltaX + 'px';
element.style.top = elementY + deltaY + 'px';
}
}
答案 6 :(得分:0)
来自 adeneo 的公认答案非常优雅并且效果很好。但是它只适用于鼠标点击,所以这是一个包含触摸输入的修改版本:
var position;
var offset = [0,0];
var isDown = false;
function makeDraggable(el){
['mousedown', 'touchstart'].forEach( evt =>
el.addEventListener(evt, pickup, true)
);
['mousemove', 'touchmove'].forEach( evt =>
el.addEventListener(evt, move, true)
);
['mouseup', 'touchend'].forEach( evt =>
el.addEventListener(evt, drop, true)
);
function pickup(e) {
isDown = true;
if (e.clientX) {
offset = [el.offsetLeft - e.clientX, el.offsetTop - e.clientY];
}
else if (e.touches) {
// for touch devices, use 1st touch only
offset = [el.offsetLeft - e.touches[0].pageX, el.offsetTop - e.touches[0].pageY];
}
}
function move(e) {
if (isDown) {
if (e.clientX) {
position = {x : e.clientX, y : e.clientY};
}
else if (e.touches) {
position = {x : e.touches[0].pageX, y : e.touches[0].pageY};
}
el.style.left = (position.x + offset[0]) + 'px';
el.style.top = (position.y + offset[1]) + 'px';
}
}
function drop(e) {
// seems not to be needed for Android Chrome
// and modern browsers on Mac & PC
// but is required for iPad & iPhone
isDown = false;
el.style.left = (position.x + offset[0]) + 'px';
el.style.top = (position.y + offset[1]) + 'px';
}
}