Reputation: 384
I want to create a web page in which a specific image is capable to drag.
so this was my code.
<! doctype html>
<html>
<head>
<title>
</title>
<script src="13.8.js"></script>
</head>
<body>
<img src="file:\\C:\Users\X555\Pictures\poster\yellowflowers.png" id="image" alt="white lion">
<script>
var mustDrag;
var image
function set() {
image = document.getElementById("image");
image.addEventListener("mousedown", function () { mustDrag = true }, false);
window.addEventListener("mouseup", function () { mustDrag = false; }, false);
window.addEventListener("mousemove", drag, false);
}
function drag(e) {
if (mustDrag) {
e.target.style.position = 'absolute';
e.target.style.left = Number(e.x);
e.target.style.top = Number(e.y);
}
}
window.addEventListener("load", set, false);
</script>
</body>
</html>
but it doesn't function correctly .sometimes it drag whit it shouldn't. and usually throw the image in lower-left side of the window while it mustn't. I don't realize at all that whats wrong with this code?
Upvotes: 1
Views: 254
Reputation: 362
Refer this Example, hope you will get your answer
function startDrag(e) {
// determine event object
if (!e) {
var e = window.event;
}
if(e.preventDefault) e.preventDefault();
// IE uses srcElement, others use target
targ = e.target ? e.target : e.srcElement;
if (targ.className != 'dragme') {return};
// calculate event X, Y coordinates
offsetX = e.clientX;
offsetY = e.clientY;
// assign default values for top and left properties
if(!targ.style.left) { targ.style.left='0px'};
if (!targ.style.top) { targ.style.top='0px'};
// calculate integer values for top and left
// properties
coordX = parseInt(targ.style.left);
coordY = parseInt(targ.style.top);
drag = true;
// move div element
document.onmousemove=dragDiv;
return false;
}
function dragDiv(e) {
if (!drag) {return};
if (!e) { var e= window.event};
// var targ=e.target?e.target:e.srcElement;
// move div element
targ.style.left=coordX+e.clientX-offsetX+'px';
targ.style.top=coordY+e.clientY-offsetY+'px';
return false;
}
function stopDrag() {
drag=false;
}
window.onload = function() {
document.onmousedown = startDrag;
document.onmouseup = stopDrag;
}
.dragme{
position:relative;
width: 270px;
height: 203px;
cursor: move;
}
#draggable {
background-color: #ccc;
border: 1px solid #000;
}
<img src="https://lh4.googleusercontent.com/-8tqTFxi2ebU/Ufo4j_thf7I/AAAAAAAADFM/_ZBQctm9e8E/w270-h203-no/flower.jpg" alt="drag-and-drop image script"
title="drag-and-drop image script" class="dragme">
<div id="draggable" class="dragme">Test </div>
Upvotes: 3