這篇文章將為大家詳細講解有關使用JavaScript實現一個拉拽效果,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
代碼如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
#drag {
background: aqua;
width: 200px;
height: 200px;
position: absolute;
-moz-user-select: none;
-khtml-user-select: none;
user-select: none;
}
#parent {
position: relative;
background: #cde4dc;
height: 80vh;
overflow: hidden;
}
</style>
</head>
<body>
<section id="parent">
<div id="drag"><div>這是一個測試</div></div>
</section>
<script type="text/javascript">
//自執行函數,需要拖拽的元素需要設置position:absolute,父元素position:relative
//有傳父親節點、若無則默認body為父節點
((parent, children, mouseType) => {
if (!children) return;
let childrenDiv = document.querySelector(children);
childrenDiv.style.position = 'absolute';
let parentDiv = parent
? document.querySelector(parent)
: document.querySelector('body');
let isDown = false;
let x,
y,
l,
t = 0;
childrenDiv.onmousedown = function (e) {
x = e.clientX;
y = e.clientY;
// 獲取左部和底部的偏移量
l = childrenDiv.offsetLeft;
t = childrenDiv.offsetTop;
isDown = true;
childrenDiv.style.cursor = mouseType || 'move';
};
// 鼠標移動
window.onmousemove = function (e) {
if (!isDown) {
return;
}
//獲取移動后的x和y坐標
let nx = e.clientX;
let ny = e.clientY;
//獲取父元素的寬高
let parentWidth = parentDiv.clientWidth;
let parentHeight = parentDiv.clientHeight;
//獲取子元素的寬高
let childrenWidth = childrenDiv.clientWidth;
let childrenHight = childrenDiv.clientHeight;
// 計算移動后的左偏移量和頂部偏移量
let nLeft = nx - (x - l);
let nTop = ny - (y - t);
let nRight = nLeft + childrenWidth;
let nBottom = nTop + childrenHight;
nLeft = nLeft <= 0 ? 0 : nLeft; //判斷左邊距離是否越界
nTop = nTop <= 0 ? 0 : nTop; //判斷上邊距離是否越界
//判斷右邊距離大于父元素寬度
if (nRight >= parentWidth) {
nLeft = parentWidth - childrenHight;
}
// 判斷下邊界是否越界
if (nBottom >= parentHeight) nTop = parentHeight - childrenHight;
childrenDiv.style.left = nLeft + 'px';
childrenDiv.style.top = nTop + 'px';
};
// 鼠標抬起事件
document.onmouseup = function (e) {
//鼠標抬起
isDown = false;
childrenDiv.style.cursor = 'default';
};
})('#parent', '#drag', 'move');
</script>
</body>
</html>
關于使用JavaScript實現一個拉拽效果就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。