//elem: Element,type: EventString, handle: EventListener
//事件处理函数
function addEvent(elem,type,handle){
if(elem.addEventListener){
elem.addEventListener(type,handle,false);
}else if(elem.attachEvent){
elem.attachEvent('on'+type,function(){
handle.call(elem);
})
}else{
elem['on' + type] = handle;
}
}
//取消事件绑定函数
function removeEvent(elem,type,handle){
if(elem.removeEventListener){
elem.removeEventListener('on' + 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{
//ie
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.pageX - parseInt(elem.style.left);
disY = event.pageY - parseInt(elem.style.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);
}
}
进行处理:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div style="left:0px;top:0px;width:100px;height:100px;background-color:aqua;position:absolute;border-radius:50%;"></div>
<script type="text/javascript" src="../../js/tools.js" ></script>
<script type = "text/javascript">
var div = document.getElementsByTagName('div')[0];
function drag(elem){
var disX,
disY;
addEvent(elem,'mousedown',function(e){
var event = e || window.event;
disX = event.pageX - parseInt(elem.style.left);
disY = event.pageY - parseInt(elem.style.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);
}
}
drag(div);
</script>
</body>
</html>
拖拽功能还有一些不太完善的地方,释放鼠标之后,div还是跟随着鼠标移动,求大神指点