(1)鼠标移动
document.onmousemove = function(e){
var event = e || window.event;
console.log(e.pageX + " " + e.pageY) //代表鼠标点击位置,MouseEvent里面包含该属性
}
(2)把移动的点绑定在div里面就能实现拖拽了
<style>
.wrapper{
width: 30px;
height:30px;
background-color: aqua;
position: absolute;
left:0;
top:0; //只要用到这两个属性就要取0;否则默认就会有auto值
}
</style>
<link href="style1.css" rel="stylesheet">
</head>
<body>
<div class="wrapper"> </div>
var div = document.getElementsByTagName('div')[0];
div.onmousedown = function(e) {
event = e || window.event;
document.onmousemove = function(e){ // document改为div也行,但是会出现鼠标跟丢的现象,document就不会
event = e || window.event;
div.style.left = event.pageX -15 + "px"; // 减去长宽的一半,保证点击位置时刻在中央
div.style.top = event.pageY -15 + "px";
}
div.onmouseup = function () {
document.onmousemove = null;
}
}
div.setCapture(); IE里面的事件捕获:会把当前所有事件都绑定在div上面
div.releaseCapture(); 这两个知道就好,不用操作
封装起来的样子:没写部分不懂