<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JS Event鼠标拖拽事件</title>
<style>
#box{width:200px;height:200px;background:#000;position:absolute;}
</style>
</head>
<body>
<div id="box"></div>
<script>
window.onload=function(){ //onload 加载页面;
var oBox=document.getElementById("box"); //找对象
document.onmousemove=function(ev){ //通常在document中添加事件,不在body中添加事件;添加onmousemove鼠标事件;绑定在事件的匿名函数,值可以有一个参数,并且它就是事件对象;
var l=ev.clientX;
var t=ev.clientY;
//console.log(l); //控制台显示鼠标的xy轴坐标
oBox.style.left=l+"px";
oBox.style.top=t+"px"; //div盒子跟随鼠标动,鼠标在document浏览器窗口中移动到哪,div盒子跟随到哪
};
};
</script>
</body>
</html>
=======================装作是 华丽的分割线===============================================
//解决鼠标动盒子跟着动的问题,改为 鼠标点击一下之后,盒子才跟着鼠标动
<script>
window.onload=function(){
var oBox=document.getElementById("box");
oBox.onmousedown=function(){
document.onmousemove=function(ev){
var l=ev.clientX;
var t=ev.clientY;
//console.log(l);
oBox.style.left=l+"px";
oBox.style.top=t+"px";
};
};
};
</script>
=======================装作是 华丽的分割线===============================================
//解决 鼠标点击一下之后,盒子才跟着鼠标动 的问题,改为 鼠标左键点击到div盒子之后开始挪动盒子,松开鼠标之后 盒子就不在动
<script>
window.onload = function() {
var oBox = document.getElementById("box");
oBox.onmousedown = function() {
document.onmousemove = function(ev) {
var l = ev.clientX;
var t = ev.clientY;
//console.log(l);
oBox.style.left = l + "px";
oBox.style.top = t + "px";
};
document.onmouseup=function(){
document.onmousemove=null;
};
};
};
</script>
=======================装作是 华丽的分割线===============================================
//解决 鼠标点击盒子挪动 时候,盒子最左上角跳动到指针的位置 的问题;
<script>
window.onload = function() {
var oBox = document.getElementById("box");
oBox.onmousedown = function(ev) {
var disX=ev.clientX-oBox.offsetLeft; //计算X轴,div盒子左边框与鼠标之间的距离
var disY=ev.clientY-oBox.offsetTop; //计算Y轴,div盒子上边框与鼠标之间的距离
document.onmousemove = function(ev) {
var l = ev.clientX-disX; //计算X轴,浏览器左边窗口与div盒子左边边框的距离
var t = ev.clientY-disY; //计算Y轴,浏览器上边窗口与div盒子上边边框的距离
console.log(l);
oBox.style.left = l + "px";
oBox.style.top = t + "px";
};
document.onmouseup = function() {
document.onmousemove = null;
};
return false; //阻止默认事件的发生
};
};
</script>