2013-03-20 67 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的。