我需要测试元素的 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;
};