多个开关按钮背景颜色CSS

时间:2017-04-15 23:23:21

标签: css z-index background-color slide

我在自定义切换按钮组中遇到问题。我想按照这个演示http://codepen.io/vanderlanth/pen/yYeryP来操作我的开关按钮背景,但是当我为这个演示中的元素提供背景颜色时,滑动部分会偶尔在元素之间滑动时变得不可见。任何人都可以帮我吗?

您可以在“切换”部分下的http://labs.epcsht.com/nash/index.html查看我尝试执行的操作。

<div class="switchButtonCont">
<input type="radio" name="switch" value="Male" id="switchButton-1" hidden="hidden"/>
<label for="switchButton-1">Male</label>
<input type="radio" name="switch" value="Female" id="switchButton-2" hidden="hidden" checked/>
<label for="switchButton-2">Female</label>
<input type="radio" name="switch" value="Both" id="switchButton-3" hidden="hidden"/>
<label for="switchButton-3">Both</label>
<input type="radio" name="switch" value="Meraba" id="switchButton-4" hidden="hidden"/>
<label for="switchButton-4">Meraba</label>
</div>

您可以查看

1 个答案:

答案 0 :(得分:0)

我发了一个概念证明,但我认为你可能需要让一些JS参与其中以使其更具可扩展性......

修订标记:

<fieldset class="cont">
  <input type="radio" name="switch" id="o1">
  <label for="o1">
    Opt 1
  </label>
  <input type="radio" name="switch" id="o2">
  <label for="o2"> 
    Opt 1
  </label>
  <input type="radio" name="switch" id="o3">
  <label for="o3">
    Opt 1
  </label>
  <span class="slider"></span>
</fieldset>

demo css

*,
*:after,
*:before {
  box-sizing: border-box;
}

.cont {
  display: flex;
  border: none;
  position: relative;
  width: 100%;
  margin: 0;
  padding: 0;

  label {
    border: 1px solid;
    flex-grow: 1;
    padding: 8px;
    position: relative;
    z-index: 2;
  }

  input {
    position: absolute;
    height: 1px;
    width: 1px;
    opacity: .000001;
  }
}

.slider {
  width: 33.3333%;
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  background: #ccc;
  z-index: 1;
  transition: left .2s ease-in-out;
}

#o2:checked ~ .slider {
  left: 33.33333%;
}

#o3:checked ~ .slider {
  left: 66.66667%;
}

只是一个FYI,但在您的示例中使用hidden属性将使屏幕阅读器无法访问这些单选按钮。

如果这些实际上是按钮而不是无线电选项,您可能还想修改标记:

<div class="cont>
  <button type="button" aria-pressed="true">
    Btn 1
  </button>
  <button type="button" aria-pressed="false">
    Btn 2
  </button>
  <button type="button" aria-pressed="false">
    Btn 3
  </button>
</div>

css也需要相应调整。

希望这对你有所帮助!