2013-04-14 89 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. 

希望帮助!