简体   繁体   中英

Why it doesn't work, style.display

I have a short script. I want to check the visibility oder the Display of a div. But it doesn't work. And i have no idea why, i found some other scripts with the same Code.

I didn't get the message JA

<html>
<head>
<script>
    function test()
    {
        alert('J');
        if (document.getElementById('t').style.visibility == "visible")
        {
            alert('JA');
        }
        if (document.getElementById('t').style.display == "block")
        {
            alert('JA');
        }
    }
</script>
</head>
<body>
<div id = 't'>
    test
</div>
<input type = 'button' onClick = 'test();'>

</body>
</html>

The style property only represents the CSS directives specified in the element's style attribute therefore, both visibility and display will be empty.

What you want is computed style

var t = document.getElementById('t'),
    style = window.getComputedStyle(t);

console.log('visibility', style.visibility);
console.log('display', style.display);

JSFiddle Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM