jQuery返回相同的不透明度

3

我在尝试使用简单的动画来设置css属性opacity:

$('#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

有人能解释这种行为吗?


1
如果您正在使用0不透明度,为什么不使用.fadeIn().fadeOut()呢? - Fabrizio Mazzoni
@FabrizioMazzoni 因为我是 jQuery 宇宙的新手,所以我没有找到那个文档部分 :) 谢谢你的建议! - Andrii Abramov
4个回答

3

您正在检查thisopacity,并更改#animationTargetopacity

这应该可以实现:

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

1

很抱歉,这是我的错。

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

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

应该被替换为:

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

1
尝试使用.fadeIn().fadeOut()来实现您正在做的事情。写的代码更少。看看:visible部分,因为我不记得它是否是正确的语法!
$('#testAnimation').click(function (event) {
  if ($(this).is(':visible') {
      $(this).fadeOut();
  } else {
      $(this).fadeIn();
  }
});

我发现了一个非常有用的门面方法来实现相同的结果:http://api.jquery.com/fadetoggle/ - Andrii Abramov

0

在您的点击事件处理程序中检查$(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 的目的是什么? - Andrii Abramov
@AndriiAbramov 谢谢您的评论! - Yosvel Quintero

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接