Jquery:如果元素被隐藏,做动作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17176798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:35:29  来源:igfitidea点击:

Jquery: if element is hidden, do action?

jquerymenuopacityhiddenvisible

提问by Jens Kvist

Hello I searched a bit on the internet, but didn't find what I actualy were looking for. But anyway, what I'm looking for is some like if a element is hidden then it's gonna do an action, and then if the element is visible it's gonna do another action. In this case I'm building an show/hide menu, when you click the menu icon (with the class ".toggle") it's gonna change the opacity to 1, and when you hide the menu the icon opacity will change to 0.6 again.

你好,我在互联网上搜索了一些,但没有找到我真正想要的。但无论如何,我正在寻找的是,如果一个元素被隐藏,那么它会执行一个操作,然后如果该元素可见,它会执行另一个操作。在这种情况下,我正在构建一个显示/隐藏菜单,当您单击菜单图标(使用类“.toggle”)时,它会将不透明度更改为 1,当您隐藏菜单时,图标不透明度将再次更改为 0.6 .

Here's my code anyway:

无论如何,这是我的代码:

$(".sidebar_menu").hide();
$(".sidebar li.toggle").click(function(){
$(".sidebar_menu").animate({width: "toggle"}, 200);
// Here's where the code I can't figure out is gonna be.
});

Hope you guys wanna help me, it would be nice! Thank you.

希望你们能帮助我,那就太好了!谢谢你。

回答by supersize

this works for hiddenand visibleelements:

这适用于hiddenvisible元素:

$(".sidebar_menu").hide();
$(".sidebar li.toggle").click(function(){
  $(".sidebar_menu").animate({width: "toggle"}, 200,
    function() {
      if($(this).is(':visible')){
        $(".toggle").css({opacity: 1});
      } else if ($(this).is(':hidden')) {
        $(".toggle").css({opacity: 0.6}); 
      }; 
    })
  });
}); 

Edit:with .toggle()

编辑:.toggle()

$(".sidebar_menu").hide();
$(".sidebar li.toggle").click(function(){
  $(".sidebar_menu").toggle('slow',
    function() {
      if($(this).is(':visible')){
        $(".toggle").css({opacity: 1});
      } else if ($(this).is(':hidden')) {
        $(".toggle").css({opacity: 0.6}); 
      }; 
    })
  });
});

Here you see a small example: FIDDLE

在这里你会看到一个小例子:FIDDLE