如何使用 .hasClass 正确切换位置?

How to use .hasClass to toggle position correctly?

我曾尝试使用 .toggle 像这样在动画之间切换,但它不起作用...例如,

$('.login').toggle(
    function()
       {
          $('#panel').animate({
          height: "150", 
          padding:"20px 0",
          backgroundColor:'#000000',
          opacity:.8
          }, 500);
       },
       function()
       {
          $('#panel').animate({
          height: "0", 
          padding:"0px 0",
          opacity:.2
          }, 500);
   });

所以我转而使用带有 类 的 if 语句,但我不知道如何阻止动画再次恢复到原来的位置。

$("#navigation").click(function() {
    $("#navigation").animate( {
        top: "0px"
    }, 200);
    $("#navigation").addClass("here");
});

$("#navigation").click(function() {
    if($("#navigation").hasClass("here") ) {
        $("#navigation").animate( {
        top: "-180px"
    }, 200);
    }
});

请参阅 .toggle(fn, fn) 现在已从最新的 jQuery 库中删除,因此无法使用。还有其他方法可以做到这一点。你可以使用 .toggleClass() 并将 css 的顶部 属性 放置到 0 到 -180:

$("#navigation").click(function() {
    $(this).toggleClass('here'); // toggle it here
    $("#navigation").stop(true, true).animate( {
      top: $(this).css('top') == "0px" ? "-180px" : "0px"; // toggle the top here
    }, 200);
});

另一个建议是使用 .stop(true, true) 来阻止多次点击的奇怪行为。

您需要使用单击处理程序,然后根据 class 的呈现设置 top 值。

在您的情况下,每次点击都会触发两个处理程序,因此首先将顶部设置为 0,然后设置为 -180

$("#navigation").click(function () {
    $(this).stop().animate({
        top: $(this).hasClass("here") ? '-180px' : "0px"
    }, 200).toggleClass("here");
});

1.如果你用hasclass那么会像下面这样:

 $("#navigation").click(function () {
        if ($("#navigation").hasClass("here")) {
            $("#navigation").animate({
                top: "-180px"
            }, 200);
        }
        else {
            $("#navigation").animate({
                top: "0px"
            }, 200);
            $("#navigation").addClass("here");
        }
    });

2.toggleclass:

$("#navigation").click(function() {
$(this).toggleClass('here');
$("#navigation").animate( {
  top: $(this).css('top') == "0px" ? "-180px" : "0px";
}, 200);
});

注意:远离tog​​gleClass,因为它添加了一个在使用前知道状态的错误源。