其实就是直接写个函数,谁用谁调即可。。。。。
1.先写两个元素,开启绝对定位
#box1 {
background-color: red;
height: 200px;
width: 200px;
position: absolute;
}
#box2 {
background-color: yellow;
height: 200px;
width: 200px;
position: absolute;
top: 200px;
left: 200px;
}
<div id="box1"></div>
<div id="box2"></div>
先获取这两个元素
var box1=document.getElementById("box1");
var box2=document.getElementById("box2");
然后写个函数
function darg(obj) {
obj.onmousedown = function (event) {
// 专门兼容IE8的,阻止全选后拖拽,会自动进行搜索
if (obj.setCapture) {
obj.setCapture();
}
event = event || window.event
var ol = event.clientX - obj.offsetLeft;
var ot = event.clientY - obj.offsetTop;
document.onmousemove = function (event) {
event = event || window.event
var x = event.clientX - ol;
var y = event.clientY - ot;
obj.style.left = x + "px";
obj.style.top = y + "px";
}
document.onmouseup = function () {
// 鼠标移除和释放按下操作时,取消以下事件
document.onmousemove = null;
document.onmouseup = null;
}
// 阻止全选后拖拽,会自动进行搜索 该方法不适用IE8
return false;
}
}
当我需要调用的时候
darg(box1);
darg(box2);
完整代码
<style>
#box1 {
background-color: red;
height: 200px;
width: 200px;
position: absolute;
}
#box2 {
background-color: yellow;
height: 200px;
width: 200px;
position: absolute;
top: 200px;
left: 200px;
}
</style>
<div id="box1"></div>
<div id="box2"></div>
<script>
var box1 = document.getElementById("box1");
var box2 = document.getElementById("box2");
darg(box1);
darg(box2);
function darg(obj) {
obj.onmousedown = function (event) {
// 专门兼容IE8的,阻止全选后拖拽,会自动进行搜索
if (obj.setCapture) {
obj.setCapture();
}
event = event || window.event
var ol = event.clientX - obj.offsetLeft;
var ot = event.clientY - obj.offsetTop;
document.onmousemove = function (event) {
event = event || window.event
var x = event.clientX - ol;
var y = event.clientY - ot;
obj.style.left = x + "px";
obj.style.top = y + "px";
}
document.onmouseup = function () {
// 鼠标移除和释放按下操作时,取消以下事件
document.onmousemove = null;
document.onmouseup = null;
}
// 阻止全选后拖拽,会自动进行搜索 该方法不适用IE8
return false;
}
}
</script>
网友评论