【问题标题】:onClick div changes color and back to color when clicking on the otheronClick div 在单击另一个时更改颜色并返回颜色
【发布时间】:2014-05-23 13:37:12
【问题描述】:

我想指出我单击了哪个 div 以防止混淆,因为在我的网站上出现的弹出菜单将是相同的,只是不同的链接但相同的按钮。现在我的问题是我无法弄清楚我是如何做到这一点的。我的网站在 Wordpress 中以获取信息。文本的颜色并不重要。 代码确实有效,但我希望当我点击“juicyplants”时颜色会发生变化,而当我点击“leafyplant”时,颜色会发生变化,“juicyplants”会恢复正常。随着颜色的变化,我的意思是已经呈现的颜色。 我的代码:

HTML:

<div id="clickOne" class="clickDesign">
<h2 class="fs20 nobold">Leafy Plants</h2>
</div>
<div  id="clickTwo" class="clickDesign">
<h2 class="fs20 nobold">Juicy Plants</h2>
</div>
</div>
<div id="leafyPlants">
Leafy Test
</div>
<div id="juicyPlants">
Juicy Test
</div>

CSS:

   #leafyPlants{
        display:none;
        position:absolute;
        top:50px;
    cursor:pointer;
    }

#juicyPlants{
    display:none;
    position:absolute;
    top:50px;
    cursor:pointer;
}

h2 {
    float:left;
    display:block;
    height:40px;
    width:150px;
    cursor:pointer;
}

jQuery:

  $("#clickOne").on('click', function() {
   $("#leafyPlants").fadeIn();
   $("#juicyPlants").fadeOut();
});
$("#clickTwo").on('click', function() {
   $("#leafyPlants").fadeOut();
   $("#juicyPlants").fadeIn();
})

【问题讨论】:

标签: javascript jquery html css wordpress


【解决方案1】:

最好改变类和使用样式:

jsfiddle: http://jsfiddle.net/TrueBlueAussie/Pcn5a/2/#update

$(function () {
    $("#clickOne").on('click', function () {
        $('.clickDesign').removeClass("active");
        $(this).addClass("active");
        $("#leafyPlants").fadeIn();
        $("#juicyPlants").fadeOut();
    });
    $("#clickTwo").on('click', function () {
        $('.clickDesign').removeClass("active");
        $(this).addClass("active");
        $("#leafyPlants").fadeOut();
        $("#juicyPlants").fadeIn();
    })
});

在样式中添加:

.active{
    color: green;
}

最好是数据驱动任何菜单系统并减少代码:

JSFiddle:http://jsfiddle.net/TrueBlueAussie/Pcn5a/3/

jQuery:

$(function () {
    $('.clickDesign').on('click', function () {
        var $this = $(this);
        $('.clickDesign').removeClass("active");
        $this.addClass("active");
        // Use the id in the data-target attribute
        $target = $($this.data('target'));
        $(".target").not($target).fadeOut();
        $target.fadeIn();
    });
});

Html(具有数据目标属性)

<div>
    <div id="clickOne" class="clickDesign" data-target="#leafyPlants">
         <h2 class="fs20 nobold">Leafy Plants</h2>

    </div>
    <div id="clickTwo" class="clickDesign" data-target="#juicyPlants">
         <h2 class="fs20 nobold">Juicy Plants</h2>

    </div>
</div>
<div id="leafyPlants" class="target">Leafy Test</div>
<div id="juicyPlants" class="target">Juicy Test</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    • 2012-12-06
    • 1970-01-01
    • 2017-08-11
    相关资源
    最近更新 更多