你碰我变

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="jquery-3.2.0.min.js"></script>
<style>
*{margin: 0;padding: 0;}
#box_1{
background: #919191;
position: absolute;
100px;
height: 100px;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
#box_2{
background: blue;
position: absolute;
100px;
height: 100px;
/*top: 0;*/
/*left: 0;*/
}
</style>
</head>
<body>
<div id="box_1"></div>
<div id="box_2"></div>
</body>
<script>
var fix = $('#box_1');
var mov = $('#box_2');
mov.mousedown(function () {
$(window).mousemove(function(e){
var x = e.clientX - 50,
y = e.clientY -50;
$('#box_2').css({
left: x + 'px',
top: y + 'px'
});
judge(mov,fix);
});
});
function judge(move,fixed){
var fixedTop = fixed.offset().top ;
var fixedRight = fixed.offset().left + fixed.width();
var fixedBottom = fixed.offset().top + fixed.height();
var fixedLeft = fixed.offset().left;

var moveTop = move.offset().top + move.height();
var moveRight = move.offset().left;
var moveBottom = move.offset().top;
var moveLeft = move.offset().left + move.width();

if(fixedTop>moveTop || fixedRight<moveRight || fixedBottom<moveBottom || fixedLeft>moveLeft){
fix.css('background','#919191');
}
else{
/*console.log(fixedTop,fixedRight,fixedBottom,fixedLeft);
console.log(moveTop,moveRight,moveBottom,moveLeft);*/
fix.css('background','red');
}
}

</script>
</html>
原文地址:https://www.cnblogs.com/followMind/p/6903616.html