使用Javascript扩展div时,更改“展开”按钮文本颜色

时间:2022-11-20 11:19:32

I've created a div which is hidden until the user clicks the "expand" causing the div to expand revealing the content. When the div is expanded the word "expand" changes to "contract" and contracts the div again on click.

我创建了一个隐藏的div,直到用户点击“展开”,导致div扩展显示内容。当div扩展时,单词“expand”变为“contract”并在点击时再次收缩div。

I'd also like the color of the clickable text to change from black to red when the div is expanded but I don't know how to do this.

当div扩展时,我也希望可点击文本的颜色从黑色变为红色,但我不知道如何做到这一点。

The code I've used is as follows

我使用的代码如下

In the body:

在身体里:

<div class="container">
<div class="header"><span>Expand</span></div>
<div class="content">Here's the contents to be hidden under the expand button</div>
</div>

in the style sheet

在样式表中

.container {
    width:100%;
}
.container div {
    width:100%;
margin-bottom: 10px;
}

.container .header {
    color: #000000;
    cursor: pointer;
}

.container .header-expanded {
    color: red;
    cursor: pointer;
}

.container .content {
    display: none;
    background-color: #FFFFFF;
    color: #333333;
}

and here's the Javascript

这是Javascript

 $(".header").click(function () {

    $header = $(this);
    //getting the next element
    $content = $header.next();
    //open up the content needed - toggle the slide- if visible, slide up, if not slidedown.
    $content.slideToggle(500, function () {
        //execute this after slideToggle is done
        //change text of header based on visibility of content div
        $header.text(function () {
            //change text based on condition
            return $content.is(":visible") ? "Collapse" : "Expand";


        });
    });
});

Could someone please show me how to make the "collapse" text appear in red when the div is expanded? Sorry if this is obvious I'm very new to this.

有人可以告诉我如何在扩展div时使“折叠”文本显示为红色吗?对不起,如果这很明显,我对此很新。

thanks.

1 个解决方案

#1


2  

You can use .toggleClass(className, state)

你可以使用.toggleClass(className,state)

A boolean value to determine whether the class should be added or removed.

一个布尔值,用于确定是应添加还是删除该类。

Declare a CSS class,

声明一个CSS类,

.redColor {color : red}

Code

$header.toggleClass('redColor', $content.is(":visible"))

#1


2  

You can use .toggleClass(className, state)

你可以使用.toggleClass(className,state)

A boolean value to determine whether the class should be added or removed.

一个布尔值,用于确定是应添加还是删除该类。

Declare a CSS class,

声明一个CSS类,

.redColor {color : red}

Code

$header.toggleClass('redColor', $content.is(":visible"))