2013-03-20 68 views
0

代碼非常簡單。JavaScript:無法提醒輸出值

HTML:

<div class="simpleDiv" id="Child1" onmouseover="expandDiv(this);"></div> 

CSS:

.simpleDiv { 
    background-color: red; 
    width: 100px; 
    height: 50px; 
    margin: 5px; 
    margin-left: 50px; 
    opacity: 1; 
} 

的JavaScript:

function expandDiv(object){ 
    alert(document.getElementById(object.id).style.height); 
} 

爲什麼我不能夠提醒這樣的div的高度?如果我使用函數hasAttribute提醒id或類,那些工作正常但不能提醒元素的CSS屬性。

任何幫助表示讚賞!

回答

6

爲什麼不只是alert(object.style.height)

無論如何,它不起作用的原因是因爲elem.style.property只適用於內嵌style="..."屬性。要考慮到所有樣式,你需要這樣的:IE的

alert(window.getComputedStyle(object).height) 

舊版本不支持這一點,但它是一個非常簡單的墊片:

window.getComputedStyle = window.getComputedStyle || function(e) {return e.currentStyle;}; 
+0

即使我嘗試alert(object.style.height),它也不起作用!可以?順便說一句,謝謝你的回答。第二個作品! – 2013-03-20 14:22:30

2
function expandDiv(object){ 



    alert(document.getElementById(object.id).innerHeight); 

} 
1

使用jQuery:

alert($('#Child1').css("height"); 

或更改屬性,使用:

$('#Child1').css("height", value) 

忽略,如果你不希望JQuery的。