2011-09-01 6 views
1

요소의 offsetWidth 및 offsetHeight를 테스트해야합니다. 현재 요소가 부착 된 다음 offsetWidth 및 Height가 테스트 된 후 요소가 제거됩니다.첨부 파일없이 DOM 요소 offsetHeight 및 offsetWidth를 효율적으로 테스트하십시오.

var sizer = document.createElement('DIV'); 
sizer.innerHTML = element; //element is a string 
document.body.appendChild(sizer); 
if (sizer.offsetWidth > maxWidth) { 
    sizer.style.width = maxWidth); 
} 
document.body.removeChild(sizer); 

을하지만 그것은 매우 느립니다 :

그것은 다음과 같습니다!

편집 : 전체 코드는 :

InfoBubble.prototype.getElementSize_ = function (element, opt_maxWidth, opt_maxHeight) { 
var sizer = document.createElement('DIV'); 
sizer.style.display = 'inline'; 
sizer.style.position = 'absolute'; 
sizer.style.visibility = 'hidden'; 

if (typeof element == 'string') { 
    sizer.innerHTML = element; 
} else { 
    sizer.appendChild(element.cloneNode(true)); 
} 

document.body.appendChild(sizer); 

// If the width is bigger than the max width then set the width and size again 
if (opt_maxWidth && sizer.offsetWidth > opt_maxWidth) { 
    sizer.style.width = this.px(opt_maxWidth); 
    //size = new google.maps.Size(sizer.offsetWidth, sizer.offsetHeight); 
} 

// If the height is bigger than the max height then set the height and size 
// again 
if (opt_maxHeight && sizer.offsetHeight > opt_maxHeight) { 
    sizer.style.height = this.px(opt_maxHeight); 
    //size = new google.maps.Size(sizer.offsetWidth, sizer.offsetHeight); 
} 
var size = new google.maps.Size(sizer.offsetWidth, sizer.offsetHeight); 

document.body.removeChild(sizer); 
return size; 
}; 

답변

2

전체 페이지 redrawn-되고있을 수 있습니다 절대적 위치, 가시성 숨겨진 div 요소에서 일을 넣고, 더 빨리해야한다.

+0

관련 정보로는 생각하지 않았지만 삽입되기 전에 요소는 숨겨져 있고 절대 위치가있는 스타일입니다. sizer.style.display = '인라인'; sizer.style.position = '절대'; sizer.style.visibility = '숨김'; 여전히 느린데 특히 공정한 문제가 발생합니다. – hrdwdmrbl

0

실제 요소 크기가 조상 요소에 따라 다르므로 정밀도로이를 수행 할 수 없다고 생각합니다.

+0

큰 정확도 없이도 동일한 작업을 수행하는 방법에 대한 제안 사항이 있습니까? 이 코드는 실제로 내 자신이 아니지만 내가 사용하고있는 라이브러리에서 가져온 것입니다. 현재 내 전체 앱을 드래그하고 있습니다. 내가 해결책을 찾지 못한다면, 나는 그것만을 버릴 필요가있을 것이다. 당신의 도움을 주셔서 감사합니다. – hrdwdmrbl