通过绝对定位,在页面中随意位置设置两个div;
也就是说div 是拖动的框,div1和div2是被触碰的框;
<!DOCTYPE html>
<html> <head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#div {
width: 100px;
height: 100px;
background: pink;
position: absolute;
top: 50px;
left: 60px;
cursor: pointer;
} #div1 {
width: 100px;
height: 100px;
border: 1px solid black;
position: absolute;
top: 300px;
left: 100px;
} #div2 {
width: 100px;
height: 100px;
border: 1px solid blue;
position: absolute;
top: 200px;
left: 600px;
}
</style>
</head> <body>
<div id="div"></div>
<div id="div1"></div>
<div id="div2"></div> </body> </html>
所有的script是在写在body里面的,
<script type="text/javascript">
var Div = document.getElementById("div");
var Div1 = document.getElementById("div1");
var Div2 = document.getElementById("div2"); //第一个固定框的上下左右的值
var top1 = parseInt(getStyle(div1, "top"));
var bottom1 = parseInt(getStyle(div1, "top")) + 100;
var left1 = parseInt(getStyle(div1, "left"));
var right1 = parseInt(getStyle(div1, "left")) + 100; //第二个固定框的上下左右的值
var top2 = parseInt(getStyle(div2, "top"));
var bottom2 = parseInt(getStyle(div2, "top")) + 100;
var left2 = parseInt(getStyle(div2, "left"));
var right2 = parseInt(getStyle(div2, "left")) + 100;
//alert(top1);
var red1 = "blue";
var red2 = "red"; Div.onmousedown = function(ev) {
var o = event || ev;
//获取到鼠标点击的位置距离div左侧和顶部边框的距离
oX = o.clientX - parseInt(getStyle(Div, "left"));
oY = o.clientY - parseInt(getStyle(Div, "top"));
//当鼠标移动,把鼠标的偏移量给div
document.onmousemove = function(ev) {
var o = event || ev;
//计算出鼠标在XY方向上移动的偏移量,把这个偏移量加给DIV的左边距和上边距,div就会跟着移动
Div.style.left = o.clientX - oX + "px";
Div.style.top = o.clientY - oY + "px"; var left = parseInt(getStyle(div, "left"));
var right = parseInt(getStyle(div, "left")) + 100;
var top = parseInt(getStyle(div, "top"));
var bottom = parseInt(getStyle(div, "top")) + 100; //第鼠标框的bottom值小于第二个框的top1值
//第鼠标框的left值大于第二个框的right1值
//第鼠标框的top值大于第二个框的bottom1值
//第鼠标框的right值小于第二个框的left1值
//当这些都满足的时候,说明第鼠标框没有触碰第二个框,所以背景色不变
//否则,就是触动框了,背景色变
if (bottom < top1 || left > right1 || top > bottom1 || right < left1) {
Div1.style.background = "";
} else {
Div1.style.background = red1;
} if (bottom < top2 || left > right2 || top > bottom2 || right < left2) {
Div2.style.background = "";
} else {
Div2.style.background = red2;
} } //当鼠标按键抬起,清除移动事件
document.onmouseup = function() {
document.onmousedown = null;
document.onmousemove = null;
} } //获取属性的数值
function getStyle(obj, attr) {
if (obj.currentStyle) {
//currentStyle获取样式的值,对应的是ie浏览器
return obj.currentStyle[attr];
} else {
//同理,对应的是其他浏览器
return getComputedStyle(obj, false)[attr];
}
}
</script>