Эффективно протестируйте DOM-элемент offsetHeight & offsetWidth, не подключая - PullRequest
1 голос
/ 01 сентября 2011

У меня есть необходимость проверить offsetWidth и offsetHeight элемента.В настоящее время элемент присоединяется, а затем проверяются offsetWidth и Height, после чего элемент удаляется.

Это выглядит так:

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 ]

2 голосов
/ 01 сентября 2011

Может быть перерисована вся страница Поместите объект в абсолютно позиционный элемент div, видимый и скрытый, он должен быть быстрее.

0 голосов
/ 01 сентября 2011

Я думаю, что вы не можете сделать это с точностью, потому что истинный размер элемента зависит от его элемента-предка.

...