解决拖拽有内容的div的bug和兼容问题

<!DOCTYPE html>

<html>

 

<head>

<meta charset="UTF-8">

<title></title>

<style type="text/css">

#big {

height: 800px;

width: 800px;

background-color: #008000;

position: relative;

}

 

#small {

height: 100px;

width: 100px;

background-color: orangered;

position: absolute;

}

</style>

</head>

 

<body>

<div id="big">

拖拽有内容的div,在浏览器上都会有bug 解决FF和chrome上的bug只需要加上return false就可以了 解决低版本IE上的bug就需要用到事件捕获setCapture和释放捕获releaseCapture() 为了解决兼容问题就需要做一个判断,需要两套代码

<div id="small">

解决FF和chrome上的bug只需要加上return false就可以了

 

</div>

</div>

</body>

<script type="text/javascript">

//拖拽有内容的div,在浏览器上都会有bug

//解决FF和chrome上的bug只需要加上return false就可以了

//解决低版本IE上的bug就需要用到事件捕获setCapture和释放捕获releaseCapture()

//为了解决兼容问题就需要做一个判断,需要两套代码

var big = document.getElementById("big");

var small = document.getElementById("small");

//鼠标按下的函数

var x = 0;

var y = 0;

small.onmousedown = function(ev) {

var oEvent = ev || event;

x = oEvent.clientX - small.offsetLeft;

y = oEvent.clientY - small.offsetTop;

 

if(small.setCapture) { //在IE下

//鼠标移动的函数

small.onmousemove = mouseMove;

//鼠标抬起的函数

small.onmouseup = mouseUp;

//解决IE下有内容的拖拽情况下的bug

//用到捕获

small.setCapture();

 

} else { //在火狐下

//鼠标移动的函数

document.onmousemove = mouseMove;

//鼠标抬起的函数

document.onmouseup = mouseUp;

 

//return false可以解决有内容的拖拽情况下的bug

//但是对IE不适用

return false;

 

}

 

}

 

//定义一个鼠标移动的函数

function mouseMove(ev) {

var oEvent = ev || event;

 

var L = oEvent.clientX - x;

var T = oEvent.clientY - y;

//保证small不被拖出大框,并且实现磁性吸附的效果

if(L < 100) {

L = 0;

} else if(L > big.offsetWidth - small.offsetWidth) {

L = big.offsetWidth - small.offsetWidth;

}

if(T < 100) {

T = 0;

} else if(T > big.offsetHeight - small.offsetHeight) {

T = big.offsetHeight - small.offsetHeight;

}

small.style.left = L + "px";

small.style.top = T + "px";

 

}

//定义一个鼠标抬起的函数

function mouseUp(ev) {

this.onmousemove = null;

this.onmouseup = null;

//释放捕获,只在IE下适用,所以要做一个判断

if(this.releaseCapture) {

this.releaseCapture();

}

 

}

</script>

 

</html>

原文地址:https://www.cnblogs.com/niuniudashijie/p/6128705.html