对于拖拽框问题的解决,与浏览器的兼容
<!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>
#box1 {
width: 200px;
height: 200px;
background-color: red;
position: absolute;
/* z-index: 10; */
}
#box2 {
width: 200px;
height: 200px;
background-color: skyblue;
position: absolute;
left: 300px;
top: 300px;
}
</style>
<script>
window.onload = function () {
// 获取box1
var box1 = document.getElementById('box1')
var box2 = document.getElementById('box2')
drag(box1)
drag(box2)
function drag(obj) {
obj.onmousedown = function (event) {
// 设置obj捕获所有鼠标事件
// setCapture() 只有IE支持,但是火狐调用不会报错,chrome调用会报错
obj.setCapture && obj.setCapture()
// 解决浏览器兼容性问题
event = event || window.event
// 鼠标拖拽div点为哪个,就从哪个点改变
// div的偏移量 鼠标.clientX-obj.offsetLeft
// div的偏移量 鼠标.clientY-obj.offsetTop
var ol = event.clientX - obj.offsetLeft
var ot = event.clientY - obj.offsetTop
// 鼠标移动 相对与页面移动,所以绑定给document
document.onmousemove = function (event) {
// 兼容浏览器
event = event || window.event
// 获取坐标轴位置
var left = event.clientX - ol
var top = event.clientY - ot
// 修改obj位置
obj.style.left = left + 'px'
obj.style.top = top + 'px'
}
document.onmouseup = function () {
// 取消document.onmousemove事件
document.onmousemove = null
// 取消document.onmouseup事件
document.onmouseup = null
// 当鼠标松开,取消事件捕获
obj.releaseCapture && box1.releaseCapture()
}
return false
}
}
}
</script>
</head>
<body>
<div id="box1"></div>
<div id="box2"></div>
</body>
</html>