简体   繁体   中英

JQuery .toggle method

I have the following JavaScript/JQuery code which should make the div SideBar appear on the screen and become 1/5th the size of the body. I'm getting no errors in Firefox/Chrome console, and havve no idea why it isn't working. If I move the body of my first toggle method into the method itself it works fine, so I'm assuming I'm using the toggle method wrong.

var bodyHeight = $(window).height();
var bodyWidth = $(window).width();
sideWidth = bodyWidth / 5;

function slideSideBar() {
    $('#SideBar').toggle(
        function() {
            $("#SideBar").animate({
                opacity: 0.6,
                width: sideWidth
            }, 600);
        }, 
        function() {
            $("#SideBar").animate({
                opacity: 0,
                width: 0
            }, 600);
        });
}

The CSS is:

#SideBar { 
    height: 100%;
    width: 0%;
    opacity: 0;
    font-family: Arial, Tahoma, Verdana;
    color: white; 
    background-color: black;
}

As of jQuery 1.8, the toggle event (the version of toggle that accepted two functions) was deprecated, and as of 1.9, it was removed. More in this question and its answers .

To get the old toggle behavior, maintain your own flag (or in your case, check the opacity) and call the toggle method (not event) yourself.

Here's the flag method, since it may be more appropriate to an animate situation (note the use of stop , which you probably wanted even in <=1.8):

var bodyHeight = $(window).height();
var bodyWidth = $(window).width();
sideWidth = bodyWidth / 5;

function slideSideBar() {
    var sidebar = $("#SideBar");
    var flag = sidebar.css("opacity") != 0;

    sidebar.click(function() {
        var options = flag ? {opacity: 0, width: 0} : {opacity: 0.6, width: sideWidth};
        flag = !flag;
        sidebar.stop(true, true).animate(options, 600);
    });
}

Or actually, checking opacity is fine after the stop :

var bodyHeight = $(window).height();
var bodyWidth = $(window).width();
sideWidth = bodyWidth / 5;

function slideSideBar() {
    $("#SideBar").click(function() {
        var sidebar = $(this);
        sidebar.stop(true, true);
        sidebar.animate(
            sidebar.css("opacity") != 0 ? {opacity: 0, width: 0} : {opacity: 0.6, width: sideWidth},
            600
        );
    });
}

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