切换按钮上的Animate Div单击

时间:2014-08-26 06:27:37

标签: javascript jquery html

我想在按钮点击时切换div的边距,但似乎不起作用。这是代码和小提琴链接。我在以前的一篇文章中找到了解决方案,但仍然无法做到正确。

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

Fiddle

感谢您的帮助

4 个答案:

答案 0 :(得分:2)

此处Margin-top返回px中的值

像下面的那样做出你的决定

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

而不是

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

DEMO

答案 1 :(得分:2)

您只需要将margin-top0px进行比较,而不仅仅是0,请参阅下面的代码:

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

});

<强> Demo

答案 2 :(得分:0)

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

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

<强> Updated Fiddle here

答案 3 :(得分:0)

最好使用类而不是margin-top检查元素的状态。例如,当用户在button上立即多次点击时,您的代码会表现得很奇怪。尝试这样的事情:

$('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);
    }
});

jsFiddle Demo

相关问题