拖拽的时候,如果触发了浏览器默认行为,就会影响效果,所以需要的时候要阻止浏览器默认行为。
解决: 标准:阻止默认行为 ,return false 即可。
非标准ie:全局捕获。obj.setCapture();
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
div{width: 100px;height: 100px;background: red;position: absolute;cursor: pointer;}
#div2{background: yellow;left: 300px;}
</style>
<script type="text/javascript">
window.onload =function(){
new Drag('div1');
new Drag('div2');
} ;
function Drag(id){
var _this = this;
this.cliX = 0;
this.cliY = 0;
this.oDiv = document.getElementById(id);
this.oDiv.onmousedown = function(){
_this.fnDowm();
};
}
Drag.prototype.fnDowm = function(ev) {
var ev = ev || event;
var _this = this;
this.cliX = ev.clientX - this.oDiv.offsetLeft;
this.cliY = ev.clientY - this.oDiv.offsetTop;
document.onmousemove =function(){
_this.fnMove();
return false;
};
document.onmouseup = function(){
_this.fnUp();
};
}
Drag.prototype.fnMove = function (ev) {
var ev = ev || event;
this.oDiv.style.left = ev.clientX - this.cliX +'px';
this.oDiv.style.top = ev.clientY -this.cliY+ 'px';
}
Drag.prototype.fnUp = function (){
document.onmouseup = null;
document.onmousemove = null;
}
</script>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>