我正在尝试实现从W3schools到我的js文件的拖拽。
这是我所指的拖拽的链接。
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_draggable
下面是我的js文件,它创建了一个div,并实现了w3schools中的拖拽功能。
first.js
function makediv() {
var mydiv= document.createElement('div')
mydiv.style = "resize: both; overflow: auto; width: 500px; height: 500px; border: 2px solid black; "
mydiv.id = "mydiv"
var innerdiv= document.createElement('div')
innerdiv.id = "innerdiv"
innerdiv.style = "resize: both; overflow: auto; width: 250px; height: 250px; border: 2px solid black; "
mydiv.appendChild(innerdiv);
const body= document.querySelector('body')
body.appendChild(mydiv);
}
//W3school stuff
function dragElement(element) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
document.getElementById(element.id).onmousedown = dragMouseDown;
function dragMouseDown(e) {
console.log("e");//I'm console.log the event to check whether the function is called
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup:
console.log(e.clientX);
console.log(e.clientY);
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves:
document.onmousemove = elementDrag;
}
function elementDrag(e) {
console.log("dragging")//I'm console.log the event to check whether the function is called
console.log(e)
e = e || window.event;
e.preventDefault();
// calculate the new cursor position:
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
// set the element's new position:
element.style.top = (element.offsetTop - pos2) + "px";
element.style.left = (element.offsetLeft - pos1) + "px";
}
function closeDragElement() {
/* stop moving when mouse button is released:*/
document.onmouseup = null;
document.onmousemove = null;
}
}我正在尝试从另一个js文件中调用上述函数。我的问题就从这里开始。
second.js
makediv()
dragElement(document.getElementById("mydiv"));当我在div上按下鼠标并尝试在div上拖动时,我可以看到所有显示事件和“拖动”的日志。但是div不会在我拖动它的时候移动,它也不会被放到我鼠标向上的位置。
**所谓日志,是指我在First.js的W3schools部件中放置了一些console.log来检查函数是否正常工作。我用// console.log事件标记了这些console.log调用,以检查函数是否被调用
我真的不明白,因为日志显示dragMouseDown和elementDrag正在工作,但是div实际上没有被拖动。
下面是我的html文件:
!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css">
<title>testing</title>
<script defer type="text/javascript" src='first.js'></script>
<script defer type="text/javascript" src='second.js'></script>
</head>
<body>
</body>
</html>我的最终目标是让第一个js文件作为一个库工作,而不是使用其他第三方库,比如jqueryui。但是我被困在这里了,那个mydiv是不能拖拽的。
我是js和html的新手。任何帮助都将不胜感激!提前感谢!
发布于 2020-11-26 17:34:28
这只是你遗漏了一个CSS属性,它是position: absolute,只需添加回来。
mydiv.style = "resize: both; overflow: auto; width: 500px; height: 500px; border: 2px solid black; position: absolute"https://stackoverflow.com/questions/65017841
复制相似问题