jQuery move div left on click then right on click

2019-08-17 00:48发布

问题:

I have a div that sits just off the right of my screen (-190px). When I click another div (called coffee) I want the offscreen div to appear, then when I click the coffee div again, I want the other div to move offscreen again.

Currently my code moves it on screen then immediately back off.

$('span.coffee').click(function(){
    $('.quick_contact').animate({'right' : '0px'});
});
$('span.coffee').click(function(){
    $('.quick_contact').animate({'right' : '-190px'});
});

How can I make it so that it stops until I click on 'span.coffee' again?

回答1:

Try this

var toggle = false;
$('span.coffee').on('click', function () {
    if (toggle == false) {
        $('.quick_contact').stop().animate({
            'right': '0px'
        });
        toggle = true;
    } else {
        $('.quick_contact').stop().animate({
            'right': '-190px'
        });
        toggle = false;
    }
});


回答2:

$('div.coffee').click(function () {
    $('.quick_contact').stop().animate({
        right: this.flag ? 0 : -190
    });
    this.flag = !this.flag;
});