IE7 table cells made invisible by CSS cannot be made visible by later class changes (??)

独自空忆成欢 提交于 2019-11-29 10:51:00

I don't have IE 7 installed, but it was the same issue with IE 6. Here's what I did to fix it:

$(function() {
  $('#click').click(function() {
    $(".compact th+th,.compact td+td").toggleClass('junk',this.checked);
  });
});

The problem was with you selector. Toggling on compact would not add visibility to junk.

This is a rendering bug. IE6/7 doesn't use a proper table display model. Unfortunately I can't recall a specific name/label for this particular bug and I can't seem to find authorative resources confirming this.

At least, I found 2 CSS ways to fix this.

  1. The easiest, use visibility: hidden; instead of display: none;. Unfortunately this doesn't work nicely if you have more columns after the to-be-toggled column or have a table border. It still leaves a space. Adding position: absolute; to .junk fixes this issue in FF, but you fall back to the same rendering problem in IE.

  2. A hack which abuses the IE's erroneous ability to apply styles for <col>.

    <!DOCTYPE html>
    <html>
        <head>
            <script src="http://code.jquery.com/jquery-latest.min.js"></script>
            <script>
                $(function() {
                    $('#click').click(function() {
                        $('table').toggleClass('compact', this.checked);
                    });
                });
            </script>
            <style>
                table.compact .junk { display: none; }
            </style>
            <!--[if lte IE 7]>
            <style>
                table.compact .junk { display: block; }
                table.compact col.junk { display: none; }
            </style>
            <![endif]-->
        </head>
        <body>
            <input type="checkbox" id="click" checked>
            <table class="compact">
                <col />
                <col class="junk" />
                <tr>
                    <th>Hello</th>
                    <th class="junk">World</th>
                </tr>
                <tr>
                    <td>Foo</td>
                    <td class="junk">Bar</td>
                </tr>
                <tr>
                    <td>Foo</td>
                    <td class="junk">Bar</td>
                </tr>
            </table>
        </body>
    </html>
    

Alternatively, you can also just toggle the elements of actual interest in jQuery:

$(function() {
    $('#click').click(function() {
        $('table.compact .junk').toggle(!this.checked);
    });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!