javascript - 为什么 id = sub 显示值的 div 是 ""而不是 none

标签 javascript html css

在此代码中 css display property div with id="sub"已更改为 none,但在运行 js 代码后它显示其 css display 值为空("")

<head>
<style>
    #title {
        height: 60px;
        background-color: green;
    }  
    #sub {
        height: 100px;
        background-color: orange;
        display: none ;
    }
<!-- display for sub set to none-->
</style>
</head>
<body>
    <div id="title"  onmousedown= "showhide('sub')"></div>
    <div id= "sub"  ></div>

<script>
    function showhide(box)  {
        var border = document.getElementById(box);
        alert('div '+ box+' got');


    if(border.style.display ==="" ){
        alert( border.style.display);
        alert ('if is true so display changes to block');
        border.style.display = "block";

    }
    else{
        alert( border.style.display);
        alert ('else is true so display changes to " "');
        border.style.display = "";
   }         
</script>
</body>

最佳答案

您需要使用 getComputedStyle :

var elem = document.getElementById(box);
if (elem.currentStyle) {
    var displayStyle = elem.currentStyle.display;
} else if (window.getComputedStyle) {
    var displayStyle = window.getComputedStyle(elem, null).getPropertyValue("display");
}
alert(displayStyle);

关于javascript - 为什么 id = sub 显示值的 div 是 ""而不是 none,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37466829/

相关文章:

html - 通过单击 CSS 更改悬停下拉菜单?

html - 在 NodeJS 中更改页面标题

html - 禁用固定视口(viewport)大小的移动设备缩放

javascript - 如何将数据从弹出窗口中继到 vue.js 应用程序

javascript - JSON 模式 : represent constraint to encode object type in string type

html - 仅在台式机上显示 adsense 广告并在手机上隐藏它

html - Angular 功能区 CSS

html - 检测图像方向(横向、纵向)以正确打印 XHTML 报告

javascript - 为什么 Flask 没有收到我的 POST Blob?

javascript - 是否有任何事件可以识别滚动条点击