javascript拖拽功能
主要是通过在鼠标按下时,获取到鼠标移动的坐标,再通过鼠标的释放,确定最终位置,这里我对pageX和pageY与clientX和clientY的区别有点朦胧了,于是网上查了下
pageX/Y:
pageX/Y获取到的是触发点相对文档区域左上角距离,会随着页面滚动而改变
兼容性:除IE6/7/8不支持外,其余浏览器均支持
clientX/Y:
clientX/Y获取到的是触发点相对浏览器可视区域左上角距离,不随页面滚动而改变
兼容性:所有浏览器均支持
screenX/Y:
screenX/Y获取到的是触发点相对显示器屏幕左上角的距离,不随页面滚动而改变
兼容性:所有浏览器均支持
offsetX/Y:
offsetX/Y获取到是触发点相对被触发dom的左上角距离,不过左上角基准点在不同浏览器中有区别,其中在IE中以内容区左上角为基准点不包括边框,如果触发点在边框上会返回负值,而chrome中以边框左上角为基准点。
兼容性:IE所有版本,chrome,Safari均完美支持,Firefox不支持
layerX/Y:
layerX/Y获取到的是触发点相对被触发dom左上角的距离,数值与offsetX/Y相同,这个变量就是firefox用来替代offsetX/Y的,基准点为边框左上角,但是有个条件就是,被触发的dom需要设置为position:relative或者position:absolute,否则会返回相对html文档区域左上角的距离
兼容性:IE6/7/8不支持,opera不支持,IE9/10和Chrome、Safari均支持
html:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>对象</title> <meta name="description" content=""> <meta name="keywords" content=""> <link href="" rel="stylesheet"> <script type="text/javascript" src="samBase.js"></script> </head> <style> .div1{ width:100px; height:100px; background: yellow; position: absolute; left:0px; top:0px; cursor: move; } .div2{ width:200px; height:200px; background: green; position: absolute; left:0px; top:0px; cursor: move; } </style> <body> <div class="div1" id="div1">BEST</div> <div class="div2" id="div2">SAM</div> </body> </html>
javascript:
<script> window.onload = function(){ new Move('div1'); new Move2('div2'); } function Move(id){ var that = this; this.moveDiv = document.getElementById(id); this.divX = 0; this.divY = 0; this.moveDiv.onmousedown = function(e){ that.fnDown(e); return false; } } Move.prototype.fnDown= function(e){ var that = this; var e = e || window.event; this.divX = e.clientX - this.moveDiv.offsetLeft; this.divY = e.clientY - this.moveDiv.offsetTop; document.onmousemove = function(e){ that.fnMove(e); } document.onmouseup = function(){ that.fnUp(); } } Move.prototype.fnMove = function(e){ var that = this; var e = e || window.event; var l = e.clientX - this.divX; var t = e.clientY - this.divY; if(l< 0){ l = 0; }else if(l > document.documentElement.clientWidth-this.moveDiv.offsetWidth){ l = document.documentElement.clientWidth-this.moveDiv.offsetWidth } if(t< 0){ t = 0; }else if(t > document.documentElement.clientHeight-this.moveDiv.offsetHeight){ t = document.documentElement.clientHeight-this.moveDiv.offsetHeight } this.moveDiv.style.left =l +'px'; this.moveDiv.style.top = t+'px'; } Move.prototype.fnUp = function(){ document.onmousemove = null; document.onmousemove = null; } //继承 function Move2(id){ var that = this; Move.call(this,id); this.moveDiv.onmouseover = function(){ that.hover(); } this.moveDiv.onmouseout = function(){ that.out(); } } //继承原型方法 for(var i in Move.prototype){ Move2.prototype[i] = Move.prototype[i]; } Move2.prototype.hover = function(){ this.moveDiv.style.background='#333'; } Move2.prototype.out = function(){ this.moveDiv.style.background='green'; } </script>