我想创建一个可以拖动特定图像的网页。
这就是我的代码。
<! 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>
但它不能正常工作。有时它会拖到不应该的地方。并且通常将图像放在窗口的左下角,而它不能。我完全没有意识到这段代码有什么问题?
最佳答案
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>
关于javascript - 使用javascript和css拖动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32818714/