我在使用 HTML5 拖放时遇到问题。这是CodePen example用最小阻力的例子来说明问题。
问题是,如果我们有一个带有 overflow: hidden
的容器,部分内容可能会显得不完整,因此当我们将其拖到容器外时,浏览器创建的重影图像会显示为不完整的内容,而不是显示完整的元素。
在示例中,有两个灰色框,其中一个被溢出隐藏,因此当您拖动它时,生成的重影图像与元素的完整形状不对应。有什么方法可以强制元素在拖动因父级溢出而隐藏的剩余拖动对象时显示完整的重影图像吗?
非常感谢
解决方案
最后,感谢 freestock.tk 提供的线索我找到了适用于该示例的解决方案。诀窍是使用 position: absolute
但在附着在 body 上并对用户隐藏的克隆对象中。我们需要将以下内容添加到拖动事件中:
c2.addEventListener('dragstart', event => {
// Here we clone the element.
let clonedElement = c2.cloneNode(true);
// And we add our class with position absolute to render it
// hidden from the user.
clonedElement.classList.add('cloned');
// Then we attach the element to the body.
document.body.appendChild(clonedElement);
// And we pass this element to drag image of the drag event
// using the position of the click of the mouse to set it.
event.dataTransfer.setDragImage(clonedElement, event.offsetX, event.offsetY);
// And finally we remove the cloned element.
window.setTimeout(() => clonedElement.parentNode.removeChild(clonedElement), 350);
});
cloned
类包含以下内容:
.cloned
position absolute
width 100px
left 1000px
这是一个带有 solution 的 CodePen工作。
最佳答案
我也在拖动事件上添加了绝对位置:
let c1 = document.getElementById('c1');
let c2 = document.getElementById('c2');
c2.addEventListener('mousedown', event => {
event.currentTarget.style.position = 'absolute';
event.currentTarget.style.margin = "10px";
});
c2.addEventListener('dragstart', event => {
event.currentTarget.style.position = 'absolute';
event.currentTarget.style.margin = "10px";
console.log(event.currentTarget);
});
c2.addEventListener('dragend', event => {
event.currentTarget.style.position = 'initial';
});
链接:CODEPEN
关于javascript - 当对象因溢出而部分隐藏时,拖放会显示错误的重影图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35994197/