1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| <html>
<head>
<meta charset="utf-8" />
<title> essaie mouvenemnt canvas </title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
</head>
<body>
<div id="back"></div>
<div class="draggable" style="background-color: green;"></div>
<div class="draggable" style="top: 125px;"></div>
<script>
var maxHeight = window.innerHeight;
var midDragWidth = 20; //half width of draggable
var midDragHeight = 40; //half height of draggable
var draggables = document.getElementsByClassName("draggable");
var drags = Array.prototype.slice.call(draggables);
console.log(drags);
for (var key in drags) {
var drag = draggables[key];
drag.onmousedown = function () {
var tmpDrag = this;
document.onmousemove = function (e) {
x = e.clientX;
y = e.clientY;
if (maxHeight - midDragHeight < y) {
y = maxHeight - midDragHeight;
} else if (0 > y - midDragHeight) {
y = midDragHeight;
}
if (maxWidth - midDragWidth < x) {
x = maxWidth - midDragWidth;
} else if (0 > x - midDragWidth) {
x = midDragWidth;
}
tmpDrag.style.top = (y - midDragHeight) + "px";
tmpDrag.style.left = (x - midDragWidth) + "px";
};
};
drag.onmouseup = function () {
document.onmousemove = null;
}
}
</script>
</body>
</html> |
Partager