jQuery修改CSS的功能

jQuery function to change CSS

本文关键字:功能 CSS 修改 jQuery      更新时间:2023-09-26

我有以下功能:

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

,并希望在单击函数中添加一个进一步的函数。我是jQuery的新手,尝试学习,但仍然不理解阅读它。我以为我可以创建和附加一个if子句,但仍然与之斗争。所以我有这样的东西:

$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

如果有人能帮帮我就太好了。

谢谢。

这是你想要的吗?

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');
        });
    });
});

可能你在找类似

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

您可能还必须检查is(':visible')如何作用于从$('.year')返回的元素集。可能是当一些可见而另一些不可见时,效果不同。

edit:正如@adeneo指出的,如果集合中任何元素可见,is(':visible')返回true。

这可能对您有用,但是代码不够简洁如您的代码片段:

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