WEB前端实例,JS实现拖拽效果~

<!-- <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div{
width: 200px;
height: 200px;
background-color: red;
border-radius: 15px;
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.7);
position: absolute;
top: 300px;
left: 1000px;
}
</style>
</head>
<body>
<div></div>
<script>
let oDiv = document.querySelector('div');
let flag = false;
oDiv.addEventListener('mousedown',(e) => {
flag = true;
let x = e.offsetX;
let y = e.offsetY;
document.addEventListener('mousemove',(e) => {
let _h = window.innerHeight - oDiv.offsetHeight;
let _w = window.innerWidth - oDiv.offsetWidth;
let div_left = e.clientX -x;
let div_top = e.clientY - y;
div_top = Math.min(Math.max(0,div_top),_h);
div_left = Math.min(Math.max(0,div_left),_w);
if(flag){
oDiv.style.top = div_top + 'px';
oDiv.style.left = div_left + 'px';
}
});
});
oDiv.addEventListener('mouseup',(e) => {
flag = false;
});
</script>
</body>
</html> -->