【发布时间】:2021-12-30 16:27:00
【问题描述】:
我遵循了这个guide 并尝试自己实现代码,但是当我运行它时,我得到一个“未定义移动”错误。关于我做错了什么有什么建议吗?尝试移动脚本引用或不包括 html 标记中的事件侦听器,这会将移动限制在容器内,但似乎没有任何改变?有什么建议么?谢谢!
let moving = null;
function pickup(event) {
moving = event.target;
moving.style.height = moving.clientHeight;
moving.style.width = moving.clientWidth;
moving.style.position = 'fixed';
moving.style.zIndex = '-10';
}
function move(event) {
if (moving) {
if (event.clientX) {
// mousemove
moving.style.left = event.clientX - moving.clientWidth/2;
moving.style.top = event.clientY - moving.clientHeight/2;
} else {
// touchmove - assuming a single touchpoint
moving.style.left = event.changedTouches[0].clientX - moving.clientWidth/2;
moving.style.top = event.changedTouches[0].clientY - moving.clientHeight/2;
}
}
}
function drop(event) {
if (moving) {
if (event.currentTarget.tagName !== 'HTML') {
let target = null;
if (event.clientX) {
target = document.elementFromPoint(event.clientX, event.clientY);
} else {
target = document.elementFromPoint(event.changedTouches[0].clientX, event.changedTouches[0].clientY);
}
target.appendChild(moving);
}
// reset our element
moving.style.left = '';
moving.style.top = '';
moving.style.height = '';
moving.style.width = '';
moving.style.position = '';
moving.style.zIndex = '';
moving = null;
}
}
* {
box-sizing: border-box;
}
#container {
display: flex;
}
#container > div {
border: 1px solid gray;
padding: 1em;
height: 10em;
width: 50%;
}
#movable-element {
border: 1px solid green;
background-color: #00ff0033;
height: 100%;
width: 100%;
}
<html onmouseup="drop(event)" ontouchend="drop(event)" onmousemove="move(event)" ontouchmove="move(event)">
<head>
<title>Drag and Drop</title>
<script src="script.js"></script>
<link rel="stylesheet" href="style.css">
<body>
<div id="container">
<div id="left-parent" onmouseup="drop(event)" ontouchend="drop(event)">
<div id="movable-element" onmousedown="pickup(event)" ontouchstart="pickup(event)"></div>
</div>
<div id="right-parent" onmouseup="drop(event)" ontouchend="drop(event)"></div>
</div>
</body>
【问题讨论】:
标签: javascript html drag drop