首页 > 解决方案 > 在中使用切换按钮

问题描述

我正在尝试在<summary>元素中放置一个切换按钮,在这里使用切换按钮:https ://www.w3schools.com/howto/howto_css_switch.asp

它在 Firefox 上运行良好,但在 Chrome 上,单击切换按钮实际上会切换<details>元素而不是切换按钮。如果我改用圆形版本,如果我点击切换按钮的角(由于四舍五入而不再是灰色/蓝色的区域),我可以切换切换按钮,但如果我点击内部则不行。

我该怎么做才能让它在 Chrome 上运行?这两种行为哪一种是“正确的”?

.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input { 
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

/* Rounded sliders */
.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}
<details>
  <summary>
    <label class="switch">
      <input type="checkbox">
      <span class="slider"></span>
    </label>
  </summary>
</details>

标签: html

解决方案


我的意思是,在我看来,这并不是很好的用户体验,但为了保持简单和语义化,只需将可操作元素中的歧义与它们所需的相应事件分开即可。例如;

.switch-summary-container {
  position: relative;
  margin: 1rem;
}

.switch-summary-container aside {
  position: absolute;
  top: -.5rem;
  left: 1rem;
}

summary {
  min-height: 40px;
}

.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input { 
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

/* Rounded sliders */
.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}
<section class="switch-summary-container">
  <aside>
    <label class="switch">
      <input type="checkbox">
      <span class="slider"></span>
    </label>
  </aside>
  <details>
    <summary>
    </summary>
    Words Words Words.
  </details>
</section>


推荐阅读