js实现图片拖动代码,希望大神给代码详细的注释(解释)下。

var ie = document.all;
var nn6 = document.getElementByIdx && !document.all;
var isdrag = false;
var y, x;
var oDragObj;

function moveMouse(e) {
if (isdrag) {
oDragObj.style.top = (nn6 ? nTY + e.clientY - y : nTY + event.clientY - y) + "px";
oDragObj.style.left = (nn6 ? nTX + e.clientX - x : nTX + event.clientX - x) + "px";
return false;
}
}

function initDrag(e) {
var oDragHandle = nn6 ? e.target : event.srcElement;
var topElement = "HTML";
while (oDragHandle.tagName != topElement && oDragHandle.className != "dragAble") {
oDragHandle = nn6 ? oDragHandle.parentNode : oDragHandle.parentElement;
}
if (oDragHandle.className == "dragAble") {
isdrag = true;
oDragObj = oDragHandle;
nTY = parseInt(oDragObj.style.top + 0);
y = nn6 ? e.clientY : event.clientY;
nTX = parseInt(oDragObj.style.left + 0);
x = nn6 ? e.clientX : event.clientX;
document.onmousemove = moveMouse;
return false;
}
}

document.onmousedown = initDrag;
document.onmouseup = new Function("isdrag=false");

第1个回答  2015-05-22
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>

</head>
<body>
<div id="box1" style = 'width:100px; height: 100px; background:#ccc; position:fixed;'></div>
<!-- 注意 盒子一定要定位 position:fixed; 或者 position:absolute;-->
</body>
<script type="text/javascript">
function getPos(e){//这是一个 获取鼠标位置的函数
var oEvent = e || event;
return {x: oEvent.clientX + document.documentElement.scrollLeft || document.body.scrollLeft,
y: oEvent.clientY +document.documentElement.scrollTop || document.body.scrollTop};
}

document.getElementById('box1').onmousedown = function(e){ //你要拖动对象在mousedown的时候发生的事情
var oEvent = e || event;
var pos = getPos(oEvent);
var _this = this;
_this.style.cursor = 'move';//改变鼠标状态
_this.disY = pos.y - _this.offsetTop;
_this.disX = pos.x - _this.offsetLeft;
document.onmousemove =function(e){ //在鼠标按下的时候 并且 移动的时候 发生的事情
var oEvent = e || event;
var dpos = getPos(oEvent);
var t = dpos.y-_this.disY ; //移动的时候获取的 移动 top值
var l = dpos.x-_this.disX ;//移动的时候获取的 移动 left

_this.style.top=t + "px"; //这两条给盒子赋值
_this.style.left=l + "px";
};
document.onmouseup = function(){//鼠标弹起的时候做的事情 一些释放 操作
_this.style.cursor = 'pointer'
this.onmousemove = null;
this.onmouseup = null;
try{
_this.releaseCapture();}catch(e){}
};
try{
_this.setCapture();}catch(b){} //这里是为了 让盒子拖动的时候不要复制页面里面的其他内容
return false;

};
</script>
</html>本回答被提问者和网友采纳

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网