切换动画潜水按钮点击

Toggle Animate Div on Button Click

本文关键字:按钮 潜水 动画      更新时间:2023-09-26

我想在单击按钮时切换div的边距动画,但似乎不起作用。这是代码和小提琴链接。我在之前的一篇帖子中找到了解决方案,但仍然无法正确处理。

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

Fiddle

感谢的帮助

此处Margin-top返回px中的值,因此

像下面的一样做出决定

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

而不是

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

DEMO

您只需要比较margin-top0px,而不是仅比较0,请参阅以下代码:

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

演示

最好用类而不是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演示。

请用更新第一个条件

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

此处更新Fiddle