CSS / Javascript Show / Hide DIV using a CSS class?

前端 未结 7 1826
陌清茗
陌清茗 2020-12-20 17:14

I\'ve googled around and found many scripts for hiding and showing DIV contents, as a toggle on button click.

But they are work using ID\'s.

I would like to

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-20 18:05

    Most of the jQuery answers should be pretty easy, but seeing as your example is in regular JS, here's how to do it in JS.

    Potential downside: browsers that don't support getElementsByTagName. I tested IE7 and it works, but I'm not sure about lower.

    var divs = document.getElementsByTagName('div');
    
    var toggle = function() {    
        for (var i = 0, l = divs.length; i < l; i++) {
            if (divs[i].getAttribute('class') == 'problem') 
                if (divs[i].style.display == 'none') divs[i].style.display = '';
                else divs[i].style.display = 'none';
        }
    }
    
    document.getElementById('Toggle').onclick = toggle;
    

    Try it out: http://jsfiddle.net/robert/PkHYf/

提交回复
热议问题