简体   繁体   English

切换jQuery动画不起作用

[英]Toggling jQuery animation not working

Trying to do a simple animation on click. 尝试在点击时做一个简单的动画。 I have a panel thats hidden off to the right side (absolute positioned) when the user clicks the tab i want the panel to slide out. 当用户单击选项卡时,我有一个隐藏在右侧(绝对位置)的面板,我希望该面板滑出。 I can get the initial slide out to work but cant get the toggle to function properly 我可以将最初的幻灯片拉出来工作,但是无法使拨动开关正常工作

 $('#sideTab').click(function() {
           $('#sideCol').animate({'right':'0%'}) 
        }, function ()
            $('#sideCol').animate({'right':'-50%'})                    
        });


 $('#sideTab').toggle(function() {
           $('#sideCol').animate({'right':'0%'}) 
        }, function ()
            $('#sideCol').animate({'right':'-50%'})                    
        });

neither of these are working 这些都不起作用

fiddle: http://jsfiddle.net/BQE32/1/ 小提琴: http : //jsfiddle.net/BQE32/1/

when the green square is clicked the blue square should move left, and when its clicked again it should move back to original positioning 单击绿色方块时,蓝色方块应向左移动,再次单击时应回到原始位置。

click doesn't accept two callback functions, you can read the right property and set the proper value: click不接受两个回调函数,您可以读取right属性并设置适当的值:

$('#sideTab').click(function () {
    var $e = $('#sideCol');
    $e.animate({
       'right': $e.css('right') === '0px' ? '-50%' : '0px'
    });
});

http://jsfiddle.net/Jrs36/ http://jsfiddle.net/Jrs36/

You can also use CSS transition property and jQuery .toggleClass() method: 您还可以使用CSS transition属性和jQuery .toggleClass()方法:

CSS: CSS:

#sideCol {
   -webkit-transition: right 400ms;
   -moz-transition: right 400ms;
   -o-transition: right 400ms;
   transition: right 400ms; 
} 

#sideCol.right50 {
    right: 50%;
}

JavaScript: JavaScript:

$('#sideTab').click(function () {
    $('#sideCol').toggleClass('right50');
});
$('#sideTab').on('click', function() {
    if ($(this).hasClass('toggled') === true) {
        $(this).animate({'right': '-50%'}).removeClass('toggled');
    } else {
        $(this).animate({'right': '0'}).addClass('toggled');
    }
});

This will check if the sidebar is already 'toggled', and if it is will remove the class and animate it back out of the frame (and vice versa). 这将检查侧边栏是否已被“切换”,如果已移除,则将删除类并将其设置为动画(反之亦然)。

You can use toggle() here: 您可以在此处使用toggle()

$('#sideTab').toggle(function() {
  $('#sideCol').animate({'right':'0%'}) 
}, function() {
  $('#sideCol').animate({'right':'-50%'}) 
});

Demo 演示版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM