兼容上古IE6、上古火狐浏览器,也兼容现代浏览器
以下是在现代chrome浏览器下的效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#div1 {width: 340px; height: 260px; background: #f00; position: absolute; top: 50px; left: 200px; }
#tip {
width: 280px;
margin: 20px auto 0;
color: #F9F9F9;
}
#inn {
background-color: #00FFFF;
margin-top: 10px;
-webkit-user-select:none;
-moz-user-select:none;
-o-user-select:none;
user-select:none;
}
</style>
<script>
window.onload = function () {
var tip = document.getElementById('tip');
var oDiv = document.getElementById('div1'); var disX = 0; var disY = 0; var el = oDiv.setCapture ? oDiv : document;
tip.innerText = '我是 ' + el.nodeName + ' ,我有mousemove事件,能监听到在页面外释放鼠标的事件';
oDiv.onmousedown = function (ev) {
var oEvent = ev || event; disX = oEvent.clientX - oDiv.offsetLeft; disY = oEvent.clientY - oDiv.offsetTop;
el.onmousemove = function (ev) {
var oEvent = ev || event; var l = oEvent.clientX - disX; var t = oEvent.clientY - disY;
if(l < 0) {l = 0;} else if(l > document.documentElement.clientWidth - oDiv.offsetWidth) {l = document.documentElement.clientWidth - oDiv.offsetWidth;}
if(t < 0) {t = 0;} else if(t > document.documentElement.clientHeight - oDiv.offsetHeight) {t = document.documentElement.clientHeight - oDiv.offsetHeight;}
oDiv.style.left = l + 'px'; oDiv.style.top = t + 'px';
};
el.onmouseup = function () {el.onmousemove = null; el.onmouseup = null;
if(oDiv.releaseCapture) {oDiv.releaseCapture();}
};
if(oDiv.setCapture) {oDiv.setCapture();}
return false;
};
var stopProp = function () {
return function (ev) {
var oEvent = ev || event;
if (oEvent.stopPropagation) {
oEvent.stopPropagation();
} else {
oEvent.cancelBubble = true;
}
}
};
var inn = document.getElementById('inn');
inn.onmousedown = stopProp();
inn.onmousemove = stopProp();
inn.onmouseup = stopProp();
};
</script>
</head>
<body>
<div id="div1"><div id="inn">我不能被选中,呵呵</div><div id="tip"></div></div>
</body>
</html>