首页 > 解决方案 > 更新按钮的 aria-checked 属性在 Chrome 上但在 Firefox 上不起作用

问题描述

我尝试使用 JS 更新切换按钮的 aria-checked 属性。它在 Firefox 上运行良好,但无法在 Chrome 上切换。

当我登录 JS 时,显然属性已更新。但当我使用 Chrome devtool 查看时,实际 UI 上却没有。

这是在 codepen 上直播

Please checkout codepen link.

标签: javascripthtmlcsswebaccessibility

解决方案


e.target由于事件传播,正在选择 Chrome 中的跨度,而不是绑定事件的按钮。

使用e.currentTarget而不是 e.target,它将选择事件最初绑定的按钮,而不是它的任何子元素。

// Rectangular switch
const rect = document.querySelector("#toggle-rect");
rect.addEventListener("click", e => {
  let checked = e.currentTarget.getAttribute("aria-checked") === "true";
  console.log(checked);
  e.currentTarget.setAttribute("aria-checked", String(!checked));
});

// Rounded switch
const round = document.querySelector("#toggle-round");
round.addEventListener("click", e => {
  let checked = e.currentTarget.getAttribute("aria-checked") === "true";
  console.log(checked);
  e.currentTarget.setAttribute("aria-checked", String(!checked));
});

// Rectangular switch
const rect = document.querySelector("#toggle-rect");
rect.addEventListener("click", e => {
  let checked = e.currentTarget.getAttribute("aria-checked") === "true";
  console.log(checked);
  e.currentTarget.setAttribute("aria-checked", String(!checked));
});

// Rounded switch
const round = document.querySelector("#toggle-round");
round.addEventListener("click", e => {
  let checked = e.currentTarget.getAttribute("aria-checked") === "true";
  console.log(checked);
  e.currentTarget.setAttribute("aria-checked", String(!checked));
});
/* reset button */

button {
  background: none;
  border: 0;
  color: inherit;
  padding: 0;
}


/* The switch - the box around the slider */

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


/* The slider */

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  /* TODO: put disable color here */
  -webkit-transition: 0.4s;
  transition: 0.4s;
}

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

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


/* Rounded sliders */

.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}


/* changing the background while toggling */

[role="switch"][aria-checked="true"] .slider {
  background-color: #2196f3;
}


/* toggling the handle */

[role="switch"][aria-checked="true"] .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}
<!-- Rectangular switch -->
<button role="switch" aria-checked="false" class="switch" id="toggle-rect">
    <span class="slider"></span>
</button>

<!-- Rounded switch -->
<button role="switch" aria-checked="false" class="switch" id="toggle-round">
    <span class="slider round"></span>
</button>


推荐阅读