1.制作一个div,能够通过鼠标对其进行拖拽
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
*{
padding: 0px;
margin: 0px;
box-sizing: border-box;
}
.box{
width: 200px;
height: 200px;
background-color: #5F9EA0;
position: relative;
top: 100px;
left: 200px;
}
</style>
</head>
<body>
<div class="box"></div>
<script type="text/javascript">
let box = document.querySelector('.box')
box.addEventListener('mousedown', (evt)=>{
// console.log(evt.clientX, evt.clientY)
// console.log(evt.pageX, evt.pageY)
// console.log(evt.offsetX, evt.offsetY)
// console.log(box.offsetLeft, box.offsetTop)
let ol = evt.offsetX
let ot = evt.offsetY
// console.log(ol, ot)
downDrag()
function downDrag(ol, ot){
box.addEventListener('mousemove', moveFunction)
}
function moveFunction(evt){
let top = evt.clientY - ot
let left = evt.clientX - ol
let rightLimit = innerWidth - parseInt(document.defaultView.getComputedStyle(box).width)
let bottomLimit = innerHeight - parseInt(document.defaultView.getComputedStyle(box).height)
// console.log(document.body.clientHeight)
if (top < 0){
top = 0
}else if (top > bottomLimit){
top = bottomLimit
}
if (left < 0){
left = 0
}else if (left > rightLimit){
left = rightLimit
}
// console.log(top, left)
box.style.top = top + 'px'
box.style.left = left + 'px'
}
window.addEventListener('mouseup', ()=>{
box.removeEventListener('mousemove', moveFunction)
})
})
// box.addEventListener('mouseup', (evt)=>{
// let divTop = evt.pageY - oldY
// let divLeft = evt.pageX - oldX
// box.style.top = divTop + document.defaultView.getComputedStyle(box).top
// box.style.left = divLeft + + document.defaultView.getComputedStyle(box).left
// })
</script>
</body>
</html>