這篇文章給大家分享的是有關原生JS如何實現拖拽位置預覽的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
效果如下:

以下是代碼實現,歡迎大家復制粘貼及吐槽。
<!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>感謝各位的閱讀!關于“原生JS如何實現拖拽位置預覽”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。