<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
#box{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
left: 0;
top: 0;
}
img{
width: 200px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
</style>
</head>
<body>
<div id="box"></div>
<img src="/JS_DOM_day05/00.jpg" alt="">
<script>
window.onload = function(){
// 确定三个点击事件
var box = document.getElementById('box');
//获取图片对象
var imgNode = document.querySelector('img');
// 鼠标按下事件
box.onmousedown = function(event){
//开启全局捕获
box.setCapture && box.setCapture();
//浏览器兼容问题
event = event || window.event;
// 鼠标的初始位置
var eleX = box.offsetLeft;
var eleY = box.offsetTop;
// 鼠标的初始值
var starX = event.clientX;
var starY = event.clientY;
// 鼠标移动事件
document.onmousemove = function(event){
// 鼠标结束的值
var endX = event.clientX;
var endY = event.clientY;
//鼠标移动的距离 = 鼠标结束的值 - 初始的值
var disX = endX - starX;
var disY = endY - starY;
//鼠标最后移动的值 = 初始值 + 移动的距离
var lastX = starX + disX;
var lastY = starY + disY;
// 需要设定一个范围
if(lastX < 0 ){
lastX = 0;
}else if(lastX > document.documentElement.clientWidth - box.offsetWidth){
lastX = document.documentElement.clientWidth - box.offsetWidth;
}
if(lastY < 0 ){
lastY = 0;
}else if(lastY > document.documentElement.clientHeight - box.offsetHeight){
lastY = document.documentElement.clientHeight - box.offsetHeight;
}
box.style.left = lastX + 'px';
box.style.top = lastY + 'px';
// 九空格碰撞
// 盒子的宽度 + 盒子的left值 < 图片距离视口左边的距离
var boxL = box.offsetWidth + lastX;
var imgL = imgNode.getBoundingClientRect().left;
// 盒子的高度 + 盒子的top值 < 图片距离视口顶部的距离
var boxT = box.offsetHeight + lastY;
var imgT = imgNode.getBoundingClientRect().top;
// 盒子的left值 > 图片的宽度 + 图片距视口左侧的距离
var boxR = lastX;
var imgR = imgNode.getBoundingClientRect().right;
// 盒子的top值 > 图片的高度 + 图片距离视口顶部的距离
var boxB = lastY;
var imgB = imgNode.getBoundingClientRect().bottom;
//判断是否符合条件使用||
if(boxL < imgL || boxT < imgT || boxR > imgR || boxB > imgB){
//都是false的话 则说明盒子没贴近图片
imgNode.src = '/JS_DOM_day05/00.jpg';
}else{
//如果有一个为true的话 则说明盒子贴近图片
imgNode.src = '/JS_DOM_day05/06.jpg';
}
}
// 鼠标抬起事件
document.onmouseup = function(){
// 释放全局捕获
box.releaseCapture && box.releaseCapture();
// 在抬起这个事件这 如果移动事件里改成document事件 则在抬起事件里也需要更改
box.onmouseup = document.onmousemove = null;
}
// 阻止自身别的想法
return false
}
}
</script>
</body>
</html>
// 记得修改图片路径哦!