>  기사  >  웹 프론트엔드  >  자체 js 도구 이벤트 패키징_javascript 기술

자체 js 도구 이벤트 패키징_javascript 기술

WBOY
WBOY원래의
2016-05-16 18:47:421148검색

IE의 이벤트는 전역적이고 Firefox의 이벤트는 로컬이기 때문에 사용하기가 불편합니다. 이때 일반적으로 사용되는 이벤트 작업을 직접 조립하여 쉽게 재사용할 수 있도록 클래스로 캡슐화해야 합니다.

코드 복사 코드는 다음과 같습니다.

/**
클래스 이벤트
사용법:
Event.getEvent(); ie의 이벤트를 가져옵니다.
Event.getTarget(); ie의 srcElement 또는 Firefox의 대상을 가져옵니다.
이벤트. isIe() ;ie 여부
Event.clientX(); ie,fox의 마우스 x 좌표 가져오기
Event.clientY(); ie,fox의 마우스 y 좌표 가져오기
*/
var Event=new function(){
this.toString=function(){
return this.getEvent();
}
//이벤트 가져오기
this.getEvent=function(){
var ev=window.event;
if(!ev){
var c=this.getEvent.caller;
while(c){
ev=c.arguments[0]; 🎜>if(ev && Event = =ev.constructor)
break;
c=c.caller
}
}
return ev; /이벤트 소스 가져오기
this .getTarget=function(){
var ev=this.getEvent()
return this.isIe()?ev.srcElement:ev.target
}
//즉
this.isIe=function(){
return document.all?true:false;
}
//마우스 x 좌표
this.clientX=function (){
var ev =this.getEvent();
var x=this.isIe()?ev.clientX:ev.pageX
return x; 마우스 y 좌표
this.clientY=function(){
var ev=this.getEvent()
var y=this.isIe()?ev.clientY:ev.pageY; y;
}
/**이벤트 추가(객체, 이벤트 유형, 함수 포인터)
obj: html 객체
sEvent: 이벤트 이름
spNotify: 이벤트 실행 방법
isCapture: 전체 화면 캡처 허용 여부
*/
this.addEvent=function(obj,sEvent,fpNotify,isCapture){
sEvent=sEvent.indexOf("on")!= -1?sEvent:"on" sEvent;
if(obj.addEventListener){
sEvent=sEvent.substring(sEvent.indexOf("on") 2)
obj.addEventListener(sEvent,fpNotify ,isCapture);
} else{ //즉
if(isCapture)
obj.setCapture(isCapture)
obj.attachEvent(sEvent,fpNotify)
}
}
//이벤트 제거
this.removeEvent=function(obj,sEvent,fpNotify){
if(obj.removeEventListener){
sEvent=sEvent.substring(sEvent.indexOf("on") 2)
obj.removeEventListener(sEvent,fpNotify,false);
}else{
obj.detachEvent(sEvent,fpNotify)
}
}
//마우스 가져오기 버튼, 왼쪽=1, 중간= 2, 오른쪽=3
this.button=function(){
var ev=this.getEvent()
if(!ev.which&&ev.button){/ /ie
return ev.button&1?1:(ev.button&2?3:(ev.button&4?2:0))
}
return ev.which
}; /이벤트 버블링 전달 방지
this.stopPropagation=function(){
var ev=this.getEvent()
if(this.isIe)
ev.cancelBubble=true
else;
ev.stopPropagation( );
}
//기본 이벤트 반환 방지
this.preventDefault=function(){
var ev=this.getEvent(); if(this.isIe)
ev.returnValue=false;
else
ev.preventDefault()
}
}

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.