开发者

How can i toggle to hide or show a div and class with Javascript?

Hi i just want to be able to toggle to hide/show a div 开发者_StackOverflow社区respectively with a class.

my div is ul.post_controls


Edit Sorry didn't realise you didn't mention jQuery - it just sounded so much like a jQuery question. At the same time, if you are considering using a JavaScript framework like jQuery, check out how much simpler life can be here: http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery.


You almost said it:

$('ul.post_controls').toggle();

Here's the reference: http://api.jquery.com/toggle/.


This is how I'd set it up so the uls toggle when a button is clicked:

$(document).ready(function () { // Need DOM to be ready
    $('#myButton').click(function () { // Attach click event handler
        $('ul.post_controls').toggle(); // Toggle the ul when clicked
    });
});

That's assuming you have an element with an ID of "myButton".


Non jQuery: http://www.randomsnippets.com/2008/02/12/how-to-hide-and-show-your-div/


/*
 * cssjs
 * written by Christian Heilmann (http://icant.co.uk)
 * eases the dynamic application of CSS classes via DOM
 * parameters: action a, object or name o and class names c1 and c2 (c2 optional)
 * actions: swap exchanges c1 and c2 in object o
 *          add adds class c1 to object o
 *          remove removes class c1 from object o
 *          toggle turns class c1 off if it is currently on and vice-versa
 *          check tests if class c1 is applied to object o
 * example: cssjs('swap',document.getElementById('foo'),'bar','baz');
 */

function cssjs(a,o,c1,c2)
{
    if (o) {
        switch (a){
            case 'swap':
                o.className=!cssjs('check',o,c1)?o.className.replace(c2,c1):o.className.replace(c1,c2);
                break;
            case 'add':
                if(!cssjs('check',o,c1)){o.className+=o.className?' '+c1:c1;}
                break;
            case 'remove':
                var rep=o.className.match(' '+c1)?' '+c1:c1;
                o.className=o.className.replace(rep,'');
                break;
            case 'toggle':
                cssjs('check',o,c1) ? cssjs('remove',o,c1) : cssjs('add',o,c1);
                break;      
            case 'check':
                return new RegExp('\\b'+c1+'\\b').test(o.className);
        }
    }
}o


http://rijamedia.com/blog/2011/01/simple-jquery-hideshow-elements-with-toggle-and-slidetoggle/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜