2010-06-08 3 views
2

DOM 객체의 offsetRight를 계산해야합니다. 나는 이미 offsetLeft를 얻기위한 다소 단순한 코드를 가지고 있지만, javascript offsetRight 속성은 없다. offsetLeft와 offsetWidth를 더하면 작동할까요? 아니면 더 좋은 방법이 있습니까? 당신은 다음의 다음과 같은 기능을 시도 일부 JS 라이브러리를 사용에 관심이 있다면javascript에서 offsetRight를 계산해야합니다.

function getOffsetLeft(obj) 
{ 
    if(obj == null) 
     return 0; 
    var offsetLeft = 0; 
    var tmp = obj; 
    while(tmp != null) 
    { 
     offsetLeft += tmp.offsetLeft; 
     tmp = tmp.offsetParent; 
    } 
    return offsetLeft; 
} 

function getOffsetRight(obj) 
{ 
    if (obj == null) 
     return 0; 
    var offsetRight = 0; 
    var tmp = obj; 
    while (tmp != null) 
    { 
     offsetRight += tmp.offsetLeft + tmp.offsetWidth; 
     tmp = tmp.offsetParent; 
    } 
    return offsetRight;  
} 
+0

"offsetRight"로 무엇을 하시겠습니까? "left"와 "top"이유는 윈도우의 왼쪽 상단 (또는 실제로는 컨테이너 상자)이 고정되어 있다는 것입니다. 뷰 프레임 늘이기/축소는 오른쪽과 아래쪽에서 (개념적으로) 발생합니다. – Pointy

+0

나는 현재 오브젝트 뒤에 div를 그리고, 오른쪽에서 왼쪽으로 언어를 사용하고있다. 객체 (텍스트)가 오른쪽에서 끝나는 부분을 알아야 div의 오른쪽 가장자리를 어디에 배치해야하는지 알 수 있습니다. DOM의 모든 것이 왼쪽에서 오른쪽으로 작동하기 때문에 이것은 두통입니다. –

답변

2
//Object references 
function getObject(id) { 
    var object = null; 
    if (document.layers) { 
    object = document.layers[id]; 
    } else if (document.all) { 
    object = document.all[id]; 
    } else if (document.getElementById) { 
    object = document.getElementById(id); 
    } 
    return object; 
} 
//Get pixel dimensions of screen 
function getDimensions(){ 
    var winW = 630, winH = 460; 
    if (document.body && document.body.offsetWidth) { 
    winW = document.body.offsetWidth; 
    winH = document.body.offsetHeight; 
    } 
    if (document.compatMode=='CSS1Compat' && document.documentElement && document.documentElement.offsetWidth) { 
    winW = document.documentElement.offsetWidth; 
    winH = document.documentElement.offsetHeight; 
    } 
    if (window.innerWidth && window.innerHeight) { 
    winW = window.innerWidth; 
    winH = window.innerHeight; 
    } 
    return{"width":winW, "height":winH} 
} 
//Get the location of element 
function getOffsetRight(elem){ 
    element=getObject(elem) 
    var width = element.offsetWidth 
    var right = 0; 
    while (element.offsetParent) { 
     right += element.offsetLeft; 
     element = element.offsetParent; 
    } 
    right += element.offsetLeft; 
    right = getDimensions()["width"]-right 
    right -= width 
    return right 
} 

이 아니다 방탄하지만 당신은 일반적으로 호출하여 "offsetRight"를 얻을 수 있습니다 : getOffsetRight ("[object.id]")

관련 문제