鼠标事件-拖拽(不能拖出窗口的div)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#div2 {
width: 150px;
height: 150px;
position: absolute;
background: #CCCCCC;
}
</style>
<script>
window.onload = function() {
var div2 = document.getElementById('div2');
var x = 0;
var y = 0;
document.onmousedown = function(ev) {
var oEvent = ev || event;
//x、y分别代表,鼠标与div之间的横坐标和纵坐标
x = oEvent.clientX - div2.offsetLeft;
y = oEvent.clientY - div2.offsetTop;
document.onmousemove = function(ev) {
var oEvent = ev || event;
//m、n分别代表div的横、纵坐标
var m = oEvent.clientX - x;
var n = oEvent.clientY - y;
//下面两个if else 阻止div飞出页面
if(m < 0){
m = 0;
}
//document.documentElement.clientWidth获取整个页面的宽度
else if(m > (document.documentElement.clientWidth - div2.offsetWidth)){
m = document.documentElement.clientWidth - div2.offsetWidth;
}
if(n < 0){
n =0;
}
else if(n > (document.documentElement.clientHeight - div2.offsetHeight)){
n = document.documentElement.clientHeight - div2.offsetHeight;
}
//设置div的坐标
div2.style.left = m + 'px' ;
div2.style.top = n + 'px';
};
document.onmouseup = function(ev){
var oEvent = ev || event;
//释放move事件,如果不释放,放开鼠标后,div仍然会跟随鼠标移动
document.onmousemove = null;
document.onmouseup = null;
};
};
};
</script>
</head>
<body>
<div id="div2"></div>
</body>
</html>