Javascript 在按钮上切换动画Div单击

Javascript 在按钮上切换动画Div单击,javascript,jquery,html,Javascript,Jquery,Html,我想在单击按钮时切换div边距的动画,但似乎不起作用。下面是代码和fiddle链接。我在之前的一篇文章中找到了解决方案,但仍然无法正确实现 $('button').click(function () { if ($('.demo').css('margin-top') == '0') { $('.demo').animate({ marginTop: '-160px' }, 1000); } else { $

我想在单击按钮时切换div边距的动画,但似乎不起作用。下面是代码和fiddle链接。我在之前的一篇文章中找到了解决方案,但仍然无法正确实现

$('button').click(function () {
    if ($('.demo').css('margin-top') == '0') {
        $('.demo').animate({
            marginTop: '-160px'
        }, 1000);
    } else {
        $('.demo').animate({
            marginTop: '0'
        }, 1000);
    }
});


感谢您的帮助

此处
margintop
返回
px中的值
so

像贝娄一样做决定

 if ($('.demo').css('margin-top') == '0px') {...}
而不是

  if ($('.demo').css('margin-top') == '0') {..}

您只需将
页边距顶部
0px
进行比较,而不仅仅是
0
,请参见下面的代码:

$('button').click(function () {
    if ($('.demo').css('margin-top') == '0px') {
        $('.demo').animate({
            marginTop: '-160px'
        }, 1000);
    } else {
        $('.demo').animate({
            marginTop: '0'
        }, 1000);
    }

});

请使用以下内容更新第一个条件:

if ($('.demo').css('margin-top') == '0px') {

最好用类检查元素的状态,而不是
页边空白顶部
。例如,当用户立即多次单击
按钮
,您的代码将表现得异常。试着这样做:

$('button').click(function () {
    if (! $('.demo').hasClass('done')) {
        $('.demo').addClass('done');
        $('.demo').stop().animate({
            marginTop: '-160px'
        }, 1000);
    } else {
        $('.demo').removeClass('done');
        $('.demo').stop().animate({
            marginTop: '0'
        }, 1000);
    }
});

.

'0'
更改为
'0px'
@Vinet G Nair我认为您有许多解决方案正在发挥作用。因此,请勾选对您有效的答案。。谢谢。完成了尤努斯…新到堆栈。。不太了解所有的事情。。谢谢你说当用户立即点击多次时,代码会表现得很奇怪。你有没有试着在小提琴上多次点击按钮??如果没有,请试试看。@Yunus是的,我试过了。当用户单击时,它将滑动,当用户再次单击时,滑动将停止,菜单将向下滑动(用户中断上一个操作),依此类推。