function addEvent(elem,type,handle) {
if(elem.addEventListener) {//通用 IE9以下不兼容
elem.addEventListener(type,handle,false);
}else if(elem.attachEvent) {//兼容IE
elem.attachEvent('on' + type,function() {
handle.call(elem);//this本身指向window,加上call(elem)使this指向elem
})
}else{//兼容性最好,但一个事件只能绑定一个处理函数(缺陷)
elem['on' + type] = handle;
}
}
function removeEvent(elem,type,handle){
if(elem.removeEventListener){
elem.removeEventListener(type,handle,false);
}else if(elem.detachEvent){
elem.detachEvent('on'+type,handle);
}else{
elem['on'+type] = null;
}
}
function stopBubble(event) {
if(event.stopPropagation) {
event.stopPropagation();
}else{
event.cancelBubble = true;
}
}
function cancelHandler(event) {
if(event.preventDefault) {
event.preventDefault();
}else{
event.returnValue = false;
}
}
function drag(elem) {
var disX,
disY;
addEvent(elem,'mousedown',function(e) {
var event = e || window.event;
disX = event.clientX - parseInt(getstyle(elem,'left'));
disY = event.clientY - parseInt(getstyle(elem,'top'));
addEvent(document,'mousemove',mouseMove);
addEvent(document,'mouseup',mouseUp);
stopBubble(event);
cancelHandler(event);
});
function mouseMove(e) {
var event = e || window.event;
elem.style.left = event.clientX - disX + "px";
elem.style.top = event.clientY - disY + "px";
}
function mouseUp(e) {
var event = e || window.event;
removeEvent(document,'mousemove',mouseMove);
removeEvent(document,'mouseup',mouseUp);
}
}