下面的代码产生预期的结果:
<script>
function Show_Visibility(){
p = document.getElementById("i_button_2");
alert(p.style.visibility);
}
</script>
<INPUT TYPE = "button" id = "i_button_1" value = "This is Button 1" onclick="Show_Visibility()">
<br>
<INPUT TYPE = "button" id = "i_button_2" value = "This is Button 2">
<script>
p = document.getElementById("i_button_2");
p.style.visibility = "hidden";
</script>
但是,如果我们将按钮2的可见性定义为在CSS中隐藏,则在页面加载时按钮确实是隐藏的,但是Javascript警报消息为空。
#i_button_2{visibility: hidden;}
<script>
function Show_Visibility(){
p = document.getElementById("i_button_2");
alert(p.style.visibility);
}
</script>
<INPUT TYPE = "button" id = "i_button_1" value = "This is Button 1" onclick="Show_Visibility()">
<br>
<INPUT TYPE = "button" id = "i_button_2" value = "This is Button 2">
为什么会这样呢?
最佳答案
您应该使用getComputedStyle
来通过样式表应用样式:
alert(getComputedStyle(p).visibility);
从MDN文章:
从getComputedStyle返回的对象是只读的,可用于检查元素的样式(包括由元素或外部样式表设置的样式)。 elt.style对象应用于在特定元素上设置样式。