demo 1
按住鼠标进行移动的拖拽效果实现:
<!DOCTYPE html>
<html lang="zh">
<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>
.box{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
left: 0;
top: 0;
cursor: move;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
var box = document.querySelector('.box')
box.onmousedown = function (ev){
var box_offsetX = ev.offsetX
var box_offsetY = ev.offsetY
document.onmousemove = function (event){
var x = event.pageX
var y = event.pageY
var box_left = x - box_offsetX
var box_top = y - box_offsetY
if (box_left <= 0) {
box_left = 0
}
if (box_left >= document.documentElement.clientWidth-box.clientWidth) {
box_left = document.documentElement.clientWidth-box.clientWidth
}
if (box_top <= 0) {
box_top = 0
}
if (box_top >= document.documentElement.clientHeight-box.clientHeight) {
box_top = document.documentElement.clientHeight-box.clientHeight
}
box.style.left = box_left + 'px'
box.style.top = box_top + 'px'
}
document.onmouseup = function (){
document.onmousemove = null
}
}
</script>
</body>
</html>
|