实现用鼠标拖动div块的移动,当鼠标点击哪个块时,鼠标移动,div也跟着移动,鼠标松开时,则停止移动
<!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>
div {
height: 200px;
width: 200px;
background-color: red;
position: absolute;
top: 20px;
}
#d2{
top: 220px;
background-color: aqua;
}
#d3{
top: 420px;
background-color: blueviolet;
}
body {
margin: 0px;
}
</style>
<script>
var isdown=false;// 判断鼠标是否被按下
function clickmouse(e){
isdown=true;//鼠标被按下
}
function mouseup(e){
isdown=false;//鼠标松开
}
function move(e,d){
var t1= document.getElementById("t1");
var x=e.clientX;//事件被触发时,鼠标指针的水平坐标。
var y=e.clientY;//事件被触发时,鼠标指针的垂直坐标。
if(isdown){
t1.value=x+","+y;
d.style.left=(x-100)+"px";//让鼠标显示在div块的中间,减去1/2的div块的宽度
d.style.top=(y-100)+"px"; //让鼠标显示在div块的中间,减去1/2的div块的高度
}
}
</script>
</head>
<body >
<div onmousedown="clickmouse(event)" onmousemove="move(event,this)" onmouseup="mouseup(event)" id="d1"></div>
<div onmousedown="clickmouse(event)" onmousemove="move(event,this)" onmouseup="mouseup(event)" id="d2"></div>
<div onmousedown="clickmouse(event)" onmousemove="move(event,this)" onmouseup="mouseup(event)" id="d3"></div>
<input type="text" id="t1">
</body>
</html>
下面是运行效果