<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
//清除页面内外间距
* {
margin:0;
padding:0;
}
//设置蓝色方块样式
#blue {
width:100px;
height:100px;
background:blue;
position:absolute;
}
//设置红色方块样式
#red{
width:100px;
height:100px;
background:red;
position:absolute;
top:40%;
left:60%;
}
</style>
</head>
<body>
<----页面两个方块---->
<div id="blue"></div>
<div id="red"></div>
<script>
//蓝色方块按下事件
blue.onmousedown = function(e) {
var e = e || window.event;
//获取鼠标点击距离
var left = e.offsetX;
var top = e.offsetY;
//蓝色方块移动事件
window.onmousemove = function(e) {
var e = e || window.event;
blue.style.left = e.clientX - left + "px";
blue.style.top = e.clientY - top + "px";
//判断蓝色方块进行拖拽时情况
if(blue.offsetLeft + blue.offsetWidth < red.offsetLeft ||
blue.offsetTop + blue.offsetHeight < red.offsetTop ||
blue.offsetLeft > red.offsetWidth + red.offsetLeft ||
blue.offsetTop > red.offsetTop + red.offsetHeight) {
red.style.background = "";
red.style.zIndex = "0";
} else {
red.style.background = "pink";
blue.style.zIndex = "1";
}
}
}
//蓝色方块松开时清除移动事件
window.onmouseup = function() {
window.onmousemove = "";
}
//红色方块按下事件
red.onmousedown = function(e) {
var e = e || window.event;
//获取鼠标点击距离
var left = e.offsetX;
var top = e.offsetY;
//红色方块移动事件
window.onmousemove = function(e) {
var e = e || window.event;
red.style.left = e.clientX - left + "px";
red.style.top = e.clientY - top + "px";
//判断红色方块进行拖拽时情况
if(red.offsetLeft + red.offsetWidth < blue.offsetLeft ||
red.offsetTop + red.offsetHeight < blue.offsetTop ||
red.offsetLeft > blue.offsetWidth + blue.offsetLeft ||
red.offsetTop > blue.offsetTop + blue.offsetHeight) {
blue.style.background = "";
blue.style.zIndex = "0";
} else {
blue.style.background = "green";
red.style.zIndex = "1";
}
}
}
//红色方块松开时清除移动事件
window.onmouseup = function() {
window.onmousemove = "";
}
</script>
</body>
</html>
网友评论