【发布时间】:2015-08-17 19:51:22
【问题描述】:
我正在尝试在不使用 jquery 的情况下在 JavaScript 中创建自己的单击和拖动功能。我知道 jquery 很容易实现,但我更喜欢我自己的代码。我所拥有的,当我单击 div,然后移动鼠标时,div 移动到同一个位置并且没有实现“拖动”外观。我不确定这是为什么。我希望我的结果能够将 div 移动到图像上,这样我就可以根据 div 等“裁剪”图像。我的代码是:
index.js
function _(element) {
return document.getElementById(element);
}
index.css
body {
background-color: rgb(33, 66, 99);
margin: 0px;
padding: 0px;
}
img {
position:absolute;
}
.selection {
width: 200px;
height: 200px;
background-color: rgb(255,255,255);
position: absolute;
}
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8"/>
<title>Image Cropping</title>
<link rel = "stylesheet" href = "index.css"/>
<script src = "index.js"></script>
</head>
<body>
<div class = "image">
<img src = "model.jpg" alt = "Model" id = "theImage"/>
<div class = "selection" id = "selection"/>
</div>
<script>
_("theImage").ondragstart = function() { return false; };
var m = _("selection");
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) {
var x = m.style.left;
var y = m.style.top;
var mouseX = e.clientX;
var mouseY = e.clientY;
m.style.top += (mouseX - x) + "px";
m.style.left += (mouseY - y) + "px";
// Also tried: m.style.top = (mouseX - x) + "px";
// And : m.style.left = (mouseY - y) + "px";
}
</script>
</body>
</html>
【问题讨论】:
-
试试 Chuck Norris 的方式 -- how to implement a drag-and-drop div from scratch?
标签: javascript click drag