我整晚都在尝试解决这个问题,我确信它确实很明显,所以我希望其他人会发现我的错误,因为我只是没有更多的想法。
在一个非常简化的 Jquery 函数版本中,我有以下内容;
Jquery函数
if(!$('#map-postcode').css("opacity") == 1){
//Do some stuff first..
//Then change the css opacity of the element
$('#map-postcode').animate({opacity: 0},2000, 'linear');
}else{
//Then change the css opacity of the element
$('#map-postcode').animate({opacity: 1},2000, 'linear');
};
HTML
<input type="text" placeholder="Enter your postcode" id="map-postcode"/>
<input type="button" value="Get Directions" id="place-directions"/>
仅供引用。该函数通过按钮的“onclick”调用
我知道函数调用有效,因为文本输入确实消失了。但它永远不会回来,并且通过向 if/else 的两侧添加警报,我知道初始 if(!$('#map-postcode').css("opacity") == 1)
始终返回 true。
有人可以解释一下为什么将不透明度设置为 1 不会导致函数 else 代码块被执行。
更重要的是,有没有更好的方法来检查不透明度。
以防万一人们想知道,我不想使用 fadeToggle() 等,因为我希望元素保持“可见”(也就是说,周围元素的布局不改变),我想要淡入/淡出效果(因此使用不透明度动画)。除非有更优雅的方法来实现这一点?
最佳答案
下面的代码适合我,
$("#place-directions").click(function(){
if($('#map-postcode').css("opacity") == 1){
//Do some stuff first..
//Then change the css opacity of the element
$('#map-postcode').animate({opacity: 0},2000, 'linear');
}
else{
//Then change the css opacity of the element
$('#map-postcode').animate({opacity: 1},2000, 'linear');
};
});
我想,您在表达式之前放置的 !
运算符会造成问题。
或者,您可以使用 toggleClass()
函数 onclick,如下所示,
$("#place-directions").click(function(){
$("#map-postcode").toggleClass("fadeIt");
});
并在 CSS 中定义如下,
.fadeIt{
opacity: 0;
}
#map-postcode{
-webkit-transition: opacity 0.2s linear;
transition: opacity 0.2s linear;
}
关于如果值已动态更改,则检查元素不透明度的 Jquery 函数将失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30469640/