공통 원생 js 함수
4133 단어 JavaScript 베이스 시작
getViewportWidth: function(){
var pageWidth = window.innerWidth;
if (typeof pageWidth != "number"){
if (document.compatMode == "CSS1Compat"){
pageWidth = document.documentElement.clientWidth;
} else {
pageWidth = document.body.clientWidth;
}
}
return pageWidth;
}
2.브라우저 간 이벤트 처리 EventUtil: {
addHandler: function(element,type,handler){
if(element.addEventListener){
element.addEventListener(type,handler,false);
}else if(element.attachEvent){
element.attachEvent('on'+type, handler);
}else{
element["on"+type] = handler;
}
},
removeHandler: function(element,type,handler){
if(element.removeEventListener){
element.removeEventListener(type,handler,false);
}else if(element.detachEvent){
element.detachEvent('on'+type, handler);
}else{
element["on"+type] = null;
}
},
getEvent: function(event){
return event? event:window.event;
},
getTarget: function(event){
return event.target || event.srcElement;
},
preventDefault: function(event){
if(event.preventDefault){
event.preventDefault();
}else{
event.returnValue = false;
}
},
stopPropagation: function(event){
if(event.stopPropagation){
event.stopPropagation();
}else{
event.cancelBubble = true;
}
},
}
3. 브라우저에서 요소 거리 페이지의 맨 왼쪽과 맨 위 거리 얻기
function getElementLeft(element){
var actualLeft = element.offsetLeft;
var current = element.offsetParent;
while(current!==null){
actualLeft += current.offsetLeft;
current = current.offsetParent;
}
return actualLeft;
}
function getElementTop(element){
var actualTop = element.offsetTop;
var current = element.offsetParent;
while(current!==null){
actualTop += current.offsetTop;
current = current.offsetParent;
}
return actualLeft;
}
4. 브라우저 간 getBoundingClientRect 함수
// ,ie8 (2,2)
function getBoundingClientRect(element){
var scrollTop = document.documentElement.scrollTop;
var scrollLeft = document.documentElement.scrollLeft;
if(element.getBoundingClientRect){
if(typeof arguments.callee.offset != 'number'){
var scrollTop = document.documentElement.scrollTop;
var temp = document.createElement('div');
temp.style.cssText = "position:absolute; left:0; right:0;";
document.body.appendChid(temp);
arguments.callee.offset = -temp.getBoundingClientRect().top
-scrollTop;
document.body.removeChild(temp);
temp = null;
}
var rect = element.getBoundingClientRect();
var offset = arguments.callee.offset;
return {
left: rect.left + offset,
top: rect.top + offset,
right: rect.right + offset,
bottom: rect.bottom + offset,
}
}else{
var actualLeft = getElementLeft(element);
var actualTop = getElementTop(element);
return {
left: actualLeft - scrollLeft,
top: actualTop - scrollTop,
right: actualLeft + element.offsetWidth -scrollLeft;
bottom: actualTop + element.offsetHeight - scrollTop;
}
}
}
5. 요소가 뷰포트 범위 내에 있는지 확인
const inViewport = (el) => {
const rect = el.getBoundingClientRect()
return rect.top > 0
&& rect.bottom < window.innerHeight
&& rect.left > 0
&& rect.right < window.innerWidth
}