<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript实现元素拖动</title>
<style>
*{
margin: 0;
}
#app{
width: 100vw;
height: 100vh;
background: #9acfea;
position: relative;
}
#content{
width: 100px;
height: 100px;
position: fixed;
background: #ff6700;
border-radius: 10px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="app">
<div id="content" data-type="0"></div>
</div>
<script type="text/javascript">
let content = document.getElementById("content");
window.onmousedown = function (ev) {
/*
* 获取当前鼠标左键位置元素
* */
let ele = document.elementFromPoint(ev.clientX,ev.clientY);
/*
* 如果该位置元素属性data-type值为1则将该元素设为选中态
* */
if (ev.buttons===1 && ele.dataset.type==="0"){
ele.dataset.selected = true;
if (ev.offsetX ===0 && ev.offsetY===0){
content.dataset.x = ev.layerX.toString();
content.dataset.y = ev.layerY.toString();
} else {
content.dataset.x = ev.offsetX.toString();
content.dataset.y = ev.offsetY.toString();
}
}
};
window.onmousemove = function (ev) {
/*
* 如果有选中态元素存在,移动选中态的元素
* */
if (content.dataset.selected === "true") {
let pad_x = parseInt(content.dataset.x);
let pad_y = parseInt(content.dataset.y);
let flag = ev.clientX>pad_x &&
ev.clientX<window.innerWidth+pad_x-100 &&
ev.clientY>pad_y &&
ev.clientY<window.innerHeight+pad_y-100;
if (flag){
content.style.marginLeft = (ev.clientX-pad_x)+'px';
content.style.marginTop = (ev.clientY-pad_y)+'px';
}
}
};
window.onmouseup = function (ev) {
/*
* 鼠标左键弹起后如果有选中态元素,将它设为未选中态
* */
if (content.dataset.selected = true) {
content.dataset.selected = false;
}
}
</script>
</body>
</html>