CSS:切换时更改切换元素的背景颜色

时间:2016-02-02 10:25:44

标签: css

这是我切换元素的代码

<label style="float:right" class="toggle toggle-assertive">
             <input type="checkbox" ng-model="checkModel">
             <div class="track">
               <div class="handle"></div> 
             </div>
</label>

这是上述代码的输出 enter image description here 切换复选框后,背景元素将变为红色,如图所示 enter image description here 现在我希望切换时背景变为蓝色,所以我有这个代码

#trackBack {
background-color:#0000FF;
border:0;
}

在应用上述css代码时,无论切换与否,背景都会变为蓝色。如下图所示

enter image description here 我现在的挑战是如何在切换时将背景变为蓝色。 请帮助

2 个答案:

答案 0 :(得分:0)

您可以采取以下方式。

<强> Working Fiddle

    .onoffswitch {
        position: relative; width: 60px;
        -webkit-user-select:none; -moz-user-select:none; -ms-user-select: none;
    }
    .onoffswitch-checkbox {
        display: none;
    }
    .onoffswitch-label {
        display: block; overflow: hidden; cursor: pointer;
        height: 36px; padding: 0; line-height: 36px;
        border: 2px solid #CCCCCC; border-radius: 36px;
        background-color: #FFFFFF;
        transition: background-color 0.3s ease-in;
    }
    .onoffswitch-label:before {
        content: "";
        display: block; width: 36px; margin: 0px;
        background: #FFFFFF;
        position: absolute; top: 0; bottom: 0;
        right: 22px;
        border: 2px solid #CCCCCC; border-radius: 36px;
        transition: all 0.3s ease-in 0s; 
    }
    .onoffswitch-checkbox:checked + .onoffswitch-label {
        background-color: #0000FF;
    }
    .onoffswitch-checkbox:checked + .onoffswitch-label, .onoffswitch-checkbox:checked + .onoffswitch-label:before {
       border-color: #0000FF;
    }
    .onoffswitch-checkbox:checked + .onoffswitch-label:before {
        right: 0px; 
    }
    <div class="onoffswitch">
        <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked>
        <label class="onoffswitch-label" for="myonoffswitch"></label>
    </div>

<强> Reference link

答案 1 :(得分:0)

当你使用Jquery时,你可以使用toggleClass函数。这会更改所选html项的类。

这是Jquery的代码:

$(document).ready(function(){
    $("button").click(function(){
        $("p").toggleClass("main");
    });
});

这里是HTML的代码:

<body>

<button>Toggle class "main" for p elements</button>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p><b>Note:</b> Click the button more than once to see the toggle effect.</p>

</body>

和CSS:

.main {
    font-size: 120%;
    color: red;
}

这是一个可以玩的JSfiddle: JSFiddle