试图让它检测到每个元素何时被可拖动元素触摸,但它返回为反应 2 总是触摸,即使元素远不及反应 2
js:
dragElement(document.getElementById("draggable"));
function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
if (document.getElementById(elmnt.id + "header")) {
/* if present, the header is where you move the DIV from:*/
document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
} else {
/* otherwise, move the DIV from anywhere inside the DIV:*/
elmnt.onmousedown = dragMouseDown;
}
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup:
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves:
document.onmousemove = elementDrag;
}
function elementDrag(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:
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
touches(physical, reaction, "physical")
touches(chemical, reaction, "chemical")
}
function closeDragElement() {
/* stop moving when mouse button is released:*/
document.onmouseup = null;
document.onmousemove = null;
}
}
//draggable code^
let reacTouch;
let reacType;
var physical = document.getElementById("physical")
var chemical = document.getElementById("chemical")
var reaction = document.getElementById("draggableheader")
function touches(el1, el2, reacTouch) {
const r1 = el1.getBoundingClientRect();
const r2 = el2.getBoundingClientRect();
if (r2.left - r1.right < 1) {
console.log('touching');
}
else {
console.log('not touching');
}
}
html:
<span id='physical' class="phys">physical change</span>
<span id='chemical' class="chem">chemical change</span>
<div id="draggable">
<div id="draggableheader"></div>
</div>
CSS:
#draggable {
position: absolute;
z-index: 9;
background-color: #f1f1f1;
text-align: center;
border: 1px solid #d3d3d3;
}
#draggableheader {
padding: 10px;
cursor: move;
z-index: 10;
background-color: #2196F3;
color: #fff;
}
.phys {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
float: 1;
width: 50%;
height: 100px;
margin-top:20px;
//position: absolute;
}
.chem {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
float: 1;
width: 50%;
height: 100px;
margin-top:20px;
position: relative;
left: 300px;
}
无论如何都会不断检测化学物质是否接触,并正确检测物理接触和不接触的时间
编辑:在代码示例中添加了更多详细信息,以查看是否有其他问题,我只是误诊了问题