子元素会触发父元素的drag,如何阻止呢?求解!!!DOM 结构如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>drag</title>
</head>
<body>
<div
id="father"
draggable="true"
style="width: 200px; height: 200px; background: red"
>
<div
draggable="false"
id="child"
style="width: 50px; height: 50px; background: blue"
></div>
</div>
<script>
const father = document.querySelector("#father");
const child = document.querySelector("#child");
child.addEventListener("click", (e) => {
console.log("child click");
e.stopPropagation();
});
child.addEventListener("dragstart", (e) => {
e.stopPropagation();
});
child.addEventListener("drag", (e) => {
e.stopPropagation();
});
// =================
father.addEventListener("click", (e) => {
console.log("father click");
});
father.addEventListener("dragstart", (e) => {
console.log("father dragstart");
});
father.addEventListener("drag", (e) => {
console.log("father drag");
});
father.addEventListener("dragover", (e) => {
// console.log("father dragover");
});
father.addEventListener("dragend", (e) => {
console.log("father dragend");
});
</script>
</body>
</html>
设置子元素
draggable="true"
,然后还缺少dragend
的阻止但是这样子元素也会有拖拽效果
可以通过设置拖拽预览图setDragImage为透明图就行了
这样看着子元素就不能拖拽了