如果值已动态更改,则检查元素不透明度的 Jquery 函数将失败

标签 jquery css function

我整晚都在尝试解决这个问题,我确信它确实很明显,所以我希望其他人会发现我的错误,因为我只是没有更多的想法。

在一个非常简化的 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/

相关文章:

c# - 使用局部 View 的 MVC 4 验证

javascript - 具有多个可见项目的 jquery 滚动条

html - webkit-溢出-滚动 : touch; orientation change issue

css - 试图对齐 simple_form 框和按钮

ios - 当第一个 ScrollView 滚动时滚动第二个 Scrollview

javascript - 最后定义的原型(prototype)函数总是在对象初始化时运行

javascript - 将 PopUp 从后台移动到前台

jquery - 使用 FitText 调整 FontAwesome 图标的大小

jquery - 当一个 div 的值为 auto 时设置两个 div 的高度

function - Caml中功能的物理平等测试