简体   繁体   中英

SlideUp/SlideDown not quite working

I have a function to toggle an element:

function toggle(elemName) {
    text = document.getElementById(elemName);
    var isHidden = text.style.display == 'none';
    text.style.display = isHidden ? 'block' : 'none';

    if (text.style.display == 'none') {
        $(text).slideUp();
    }
    else {
        $(text).slideDown();
    }
    return false;
}

Really what I need is, if it is hidden, slide down, if it is visible, slide it up and make it disappear.

It is hiding and showing but the sliding does not work.

What could be wrong?

Thanks

You are hiding element before calling slideUp() or slideDown() .

Remove this line and it should work fine:

text.style.display = isHidden ? 'block' : 'none';

Hope it helps :)

Try this:

function customToggle(elemId) {
    var elem = $('#'+elemId);

    if ( elem.is(':visible') ) { elem.slideUp(); }
    else { elem.slideDown(); }
}

$(document).ready(function() {
    customToggle('myId');
});

and note that in your example $(text).slideUp(); won't work, because text will return id name only, like this: $('myId').slideUp(); and it should be like this in jQuery: $('#myId').slideUp();

Will slideToggle suit your needs?

function toggle(elemName) {
    text = document.getElementById(elemName);
    $(text).slideToggle();

}

http://jsfiddle.net/kmd97/heVEE/

See working demo http://jsfiddle.net/CAeSD/4/

You had your logic backwards, use != 'none' not == 'none' .

Also REMOVE your lines that say this:

var isHidden = text.style.display == 'none';
text.style.display = isHidden ? 'block' : 'none';

So the WORKING CODE is as follows:

function toggle(elemName) {
    text = document.getElementById(elemName);

    if (text.style.display != 'none') {
        $(text).slideUp();
    }
    else {
        $(text).slideDown();
    }
    return false;
}

$("#name").on('click', function(){
                  toggle("txt");
});

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