【问题标题】:jQuery returns the same opacityjQuery 返回相同的不透明度
【发布时间】:2017-11-29 00:04:12
【问题描述】:

我正在尝试使用带有opacity css 属性的简单动画:

$('#testAnimation').click(function (event) {
    if ($(this).css('opacity') == 0) {
        $('#animationTarget').animate({opacity: 1}, 'slow');
    } else {
        $('#animationTarget').animate({opacity: 0}, 'slow');
    }
});

第一次,元素被成功隐藏。但是当我第二次点击按钮时,$(this).css('opacity') 返回值"1"

在浏览器中调试清楚地表明opacity0

有人可以解释这种行为吗?

【问题讨论】:

  • 如果您使用的是 0 不透明度,为什么不使用 .fadeIn().fadeOut()
  • @FabrizioMazzoni 因为我是 jquery 世界的新手,所以我根本没有到达那个文档部分 :) 谢谢你的建议!

标签: javascript jquery css opacity


【解决方案1】:

好吧,这是我的错。

对于遇到类似问题的任何人,请确保您正在检查所需元素的属性:

if ($(this).css('opacity') == 0)

应替换为:

if ($('#animationTarget').css('opacity') == 0)

【讨论】:

    【解决方案2】:

    您正在检查thisopacity 并更改#animationTarget 之一。

    应该这样做:

    $('#testAnimation').click(function (event) {
      if ($('#animationTarget').css('opacity') == 0) {
        $('#animationTarget').animate({opacity: 1}, 'slow');
      } else {
        $('#animationTarget').animate({opacity: 0}, 'slow');
      }
    });
    

    【讨论】:

      【解决方案3】:

      在单击事件处理程序中检查$(this),您将引用元素$('#testAnimation')

      相反,您应该检查$('#animationTarget'),您也可以像这样重构您的代码:

      $('#testAnimation').on('click', function (event) {
          var $animationTarget = $('#animationTarget'),
              opacity = $animationTarget.css('opacity') == 0 ? 1 : 0;     
          $animationTarget.animate({opacity: opacity}, 'slow');
      });
      

      【讨论】:

      • 如果我没记错的话:$('#animationTarget').css('opacity') === 0 将始终返回 false 因为类型检查。我错了吗?以及将不透明度设置为2 的目的是什么?
      • @AndriiAbramov 感谢您的评论!
      【解决方案4】:

      尝试使用.fadeIn().fadeOut() 来实现您正在做的事情。 少写代码。看看:visible 部分,因为我不记得它是否是正确的语法!

      $('#testAnimation').click(function (event) {
        if ($(this).is(':visible') {
            $(this).fadeOut();
        } else {
            $(this).fadeIn();
        }
      });
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-08
      • 2013-05-01
      • 2013-05-07
      • 1970-01-01
      • 2023-03-11
      • 2010-12-12
      • 2010-12-05
      相关资源
      最近更新 更多