简体   繁体   English

jQuery函数更改CSS

[英]jQuery function to change CSS

I have the following function: 我有以下功能:

$(document).ready(function () {
    $('.contents').hide();
    $('.slide').click(function () {
        var $this = $(this);
        $(this).siblings('.contents').slideToggle(200, function () {
            $this.text($(this).is(':visible') ? 'close' : 'open');
        });
    });
});

and would like to add a further function to the click function. 并希望向click功能添加其他功能。 I'm new to jQuery and tried to learn but still does not understand to read it. 我是jQuery的新手,试图学习,但仍然不懂阅读。 I thought I can create and append an if-clause but still struggle with that. 我以为我可以创建并附加一个if子句,但是仍然很难解决。 So I have something like that: 所以我有这样的事情:

$this.css($('.year').is(':visible') ? 'color', 'red' : 'color', 'green');
if the click function takes place and the .contents is visible change the css setting of .year to red and if not use color green

It would be great if someone can help me out. 如果有人可以帮助我,那就太好了。

Thanks alot. 非常感谢。

Probably you looking for something like 可能您正在寻找类似的东西

$this.css( 'color', $('.year').is(':visible') ? 'red' : 'green') );

You maybe also have to check if how is(':visible') works on the set of returned elements from $('.year') . 您可能还必须检查is(':visible')$('.year')返回的元素集起作用。 Could be that is works different when some are visible and others aren't. 当一些可见而另一些不可见时,可能是不同的工作方式。

edit: as @adeneo points out, is(':visible') returns true if any element in the set is visible. 编辑:正如@a​​deneo指出的,如果集合中的任何元素is(':visible')is(':visible')返回true。

Perhaps this might work for you but the code is not as concise as your snippet: 也许这可能对您有用,但是代码却不如您的代码段那么简洁:

if ($(".year").is(":visible")) {
   $this.css({ "color" : "red" });
} else {
   $this.css({ "color" : "green" });
}

Is it what you are looking for? 是您要找的东西吗?

http://jsfiddle.net/m6WrV/4/ http://jsfiddle.net/m6WrV/4/

$(document).ready(function () {
    $('.content').hide();
    $('.slide').click(function () {
        var $this = $(this);
        $(this).siblings('.content').slideToggle(200, function () {
            $this.text($(this).is(':visible') ? 'click to close' : 'click to open');
            $(this).closest('.aai').find('.head').css('color', $(this).is(':visible') ? 'red' : 'green');
        });

    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM