Styling @Html.CheckBoxFor as a slider

若如初见. 提交于 2019-12-11 05:07:51

问题


I'm having trouble styling a checkbox generated by @Html.CheckBoxFor() as a slider.

I've identified the "culprit" to be the hidden input field. I've made a fiddle to illustrate the problem. It contains 3 checkboxes - one generated by @Html.CheckBoxFor(), the second one using the code generated by @Html.CheckBoxFor() with the hidden input commented out and the third classic checkbox.

You will see the slider is not working for the first one. I do need to use @Html.CheckBoxFor() because I want the checkbox to be bound to a property on my model, but can't figure out how to make the slider styling work...

In my view I have:

<div class="slider">
    @Html.CheckBoxFor(m => m.IsChecked, new { @class = "toggle-pill" })
    @Html.LabelFor(m => m.IsChecked, new { @class = "toggle-label" })
</div>

The .css for styling it:

.slider [type="checkbox"] {
    display: none;
}

.slider .toggle-label {
    display: block;
    width: 40px;
    height: 20px;
    position: relative;
    background: #ed495c;
    border-radius: 10px;
    transition: background 0.2s ease;
    cursor: pointer;
}

.slider .toggle-label::before {
    content: '';
    display: block;
    width: 50%;
    height: 100%;
    background: #ffffff;
    border-radius: 50%;
    box-shadow: 0 0 0 1px #d1d1d1;
    position: absolute;
    left: 0;
    top: 0;
    transition: transform 0.2s ease-in-out;
}

.slider [type="checkbox"]:checked + .toggle-label {
    background: #93ed49;
}

.slider [type="checkbox"]:checked + .toggle-label::before {
    -webkit-transform: translateX(100%);
    transform: translateX(100%);
}

The model property, IsChecked, is typeof bool.


回答1:


The issue is that your css for .slider [type="checkbox"]:checked + .toggle-label { and .slider [type="checkbox"]:checked + .toggle-label::before { use the adjacent sibling combinator (+) which selects the next sibling.

Because CheckboxFor() generates a <input type="hidden" .. /> immediately after the <input type="checkbox" .. />, the selector is choosing the wrong element (the hidden input, not the label).

You need to modify the css to use the general sibling combinator (~), so that your css becomes

.slider [type="checkbox"]:checked ~ .toggle-label {
    background: #93ed49;
}

.slider [type="checkbox"]:checked ~ .toggle-label::before {
    -webkit-transform: translateX(100%);
    transform: translateX(100%);
}

I assume your using a plugin for this, so you can either modify the original file, or add an additional css file containing the above.

Refer this forked fiddle to see how it works.



来源:https://stackoverflow.com/questions/46217712/styling-html-checkboxfor-as-a-slider

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!