给大家分享一个拖拽元素时添加预览的小Demo,效果如下:
以下是代码实现,欢迎大家复制粘贴及吐槽。
代码语言:javascript复制<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>原生JS实现拖拽位置预览</title>
<style>
.box {
position: absolute;
border: 1px dashed black;
}
#div1 {
width: 100px;
height: 100px;
background: yellow;
position: absolute;
}
</style>
<script>
window.onload = function () {
var oDiv = document.getElementById('div1');
oDiv.onmousedown = function (ev) {
var oEvent = ev || event;
var disX = oEvent.clientX - oDiv.offsetLeft;
var disY = oEvent.clientY - oDiv.offsetTop;
//创建一个虚线框的div
var oNewDiv = document.createElement('div');
oNewDiv.className = 'box';
//减去边框的大小与原div大小重合
oNewDiv.style.width = oDiv.offsetWidth - 2 'px';
oNewDiv.style.height = oDiv.offsetHeight - 2 'px';
oNewDiv.style.left = oDiv.offsetLeft 'px';
oNewDiv.style.top = oDiv.offsetTop 'px';
document.body.appendChild(oNewDiv);
document.onmousemove = function (ev) {
var oEvent = ev || event;
oNewDiv.style.left = oEvent.clientX - disX 'px';
oNewDiv.style.top = oEvent.clientY - disY 'px';
};
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
oDiv.style.left = oNewDiv.style.left;
oDiv.style.top = oNewDiv.style.top;
//移除虚线框
document.body.removeChild(oNewDiv);
};
};
};
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>