层的移动入门一
层的拖动思路为:
1、计算鼠标的偏移量:鼠标的位置-对象的位置
2、计算最后的位置:移动后鼠标位置+偏移量
ok,开始。
获取鼠标的位置:
//获取鼠标的坐标
function mouseCoords(ev)
{
if (ev.pageX || ev.pageY)
{
return {
x :ev.pageX,
y :ev.pageY
};
}
return {
x :ev.clientX + document.body.scrollLeft - document.body.clientLeft,
y :ev.clientY + document.body.scrollTop - document.body.clientTop
};
}
对象的位置:
//获取item相对于文档的位置,必须循环取得item的父级
function getPosition(e)
{
var left = 0;
var top = 0;
while (e.offsetParent)
{
left += e.offsetLeft + (e.currentStyle ? (parseInt(e.currentStyle.borderLeftWidth)).NaN0() : 0);
top += e.offsetTop + (e.currentStyle ? (parseInt(e.currentStyle.borderTopWidth)).NaN0() : 0);
e = e.offsetParent;
}
left += e.offsetLeft + (e.currentStyle ? (parseInt(e.currentStyle.borderLeftWidth)).NaN0() : 0);
top += e.offsetTop + (e.currentStyle ? (parseInt(e.currentStyle.borderTopWidth)).NaN0() : 0);
return {
x :left,
y :top
};
}
上面有个函数的扩展:NaN0()
//非数字扩展
Number.prototype.NaN0 = function()
{
return isNaN(this) ? 0 : this;
}
如此一来,就可以计算鼠标的偏移量:
//获取鼠标的偏移量
function getMouseOffset(target, ev)
{
ev = ev || window.event;
var mousePos = mouseCoords(ev);
var docPos = getPosition(target);
return {
x :mousePos.x - docPos.x,
y :mousePos.y - docPos.y
}
}
下次继续