【问题标题】:Change "Expand" button text color while div is expanded using Javascript使用 Javascript 扩展 div 时更改“扩展”按钮文本颜色
【发布时间】:2015-06-22 21:12:00
【问题描述】:

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

当 div 展开时,我还希望可点击文本的颜色从黑色变为红色,但我不知道该怎么做。

我使用的代码如下

在正文中:

<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>

在样式表中

.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;
}

这里是 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";


        });
    });
});

有人可以告诉我如何在 div 展开时使“折叠”文本显示为红色吗?抱歉,如果这很明显,我对此很陌生。

谢谢。

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

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

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

    声明一个 CSS 类,

    .redColor {color : red}
    

    代码

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

    【讨论】:

      猜你喜欢
      • 2017-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-28
      • 1970-01-01
      相关资源
      最近更新 更多