2013-04-14 86 views
0
function createCloudEntry(termName, fontSize) { 
    var div = document.createElement("div"); 
    div.innerText = termName; 
    div.style.fontSize = fontSize + "px"; 
    div.style.position = "absolute"; 
    div.style.display = "inline-block"; 
    div.style.top = getRandomPosition(0, cloudHeight - 40) + 'px'; 
    div.style.left = getRandomPosition(0, cloudWidth - 150) + 'px'; 

//document.write("Left: " + getRandomPosition(0, parseInt(cloudHeight)) + ", Top: " + getRandomPosition(0, parseInt(cloudWidth)) + "<br/>"); 
//document.write(div.style.width + " | " + div.style.height + "<br/>"); 

    return div; 

}獲取寬度和元素的高度DOM外JS

所以這是我的函數,其中我只是創造一些CSS屬性一個新的div。我的問題是,在添加到DOM之前,我可以獲取元素SO FAR的寬度和高度(在添加具有特定字體大小的文本之後)嗎?我試過window.getComputedStyle(),但它不起作用,div.style.width/height也不起作用。

+1

你是什麼意思?元素在DOM之外沒有大小,插入它的點可能會導致大小的後果。你想達到什麼目的?你爲什麼不簡單地將元素添加到DOM? –

+0

因爲我需要知道getRandomPosition()函數需要佔用多少空間,其中根據大小獲取頂部屬性和左側屬性的隨機值。 –

+0

然後將它添加到dom中,存儲尺寸並將其從dom中移除。瀏覽器不會在兩者之間重新繪製,因此用戶不可見。 –

回答

0

我使用類似的東西來臨時將其添加到DOM,然後在我拉出值後立即將其刪除。

function getElementSizing(e) 
{ 
    document.body.appendChild(e); 
    var s = {client:{w:e.clientWidth, h:e.clientHeight}, offset:{w:e.offsetWidth, h:e.offsetHeight}, scroll:{w:e.scrollWidth, h:e.scrollHeight}}; 
    document.body.removeChild(e); 
    return s; 
} 

的值會有所不同取決於元素的類型,它的定位(絕對,相對)的風格和內容,所以你會希望將它擴大到滿足您的需求。

var div = document.createElement("div"); 
div.innerText = 'some text'; 
div.style.fontSize = 12 + "px"; 
div.style.position = "absolute"; 
div.style.display = "inline-block"; 

var myDivSize = getElementSizing(div); 

console.log('DIV Client Width: '+myDivSize.client.w);//returns 46 in chrome. 
console.log('DIV Client Height: '+myDivSize.client.h);//returns 16 in chrome. 
console.log('DIV Offset Width: '+myDivSize.offset.w);//returns 46 in chrome. 
console.log('DIV Offset Height: '+myDivSize.offset.h);//returns 16 in chrome. 
console.log('DIV Scroll Width: '+myDivSize.scroll.w);//returns 46 in chrome. 
console.log('DIV Scroll Height: '+myDivSize.scroll.h);//returns 16 in chrome. 

希望幫助!