Bootstrap 用JavaScript在加载时将“checked”添加到单选按钮

7jmck4yq  于 12个月前  发布在  Bootstrap
关注(0)|答案(1)|浏览(143)

基于Bootstrap 5的暗模式开关JavaScript(https://getbootstrap.com/docs/5.3/customize/color-modes/#javascript),我试图在页面加载时以及颜色模式更改时将单选按钮设置为“checked”。
使用以下JavaScript:

<script>
      (() => {
        'use strict'

        const getStoredTheme = () => localStorage.getItem('theme')
        const setStoredTheme = theme => localStorage.setItem('theme', theme)

        const getPreferredTheme = () => {
          const storedTheme = getStoredTheme()
          if (storedTheme) {
            return storedTheme
          }

          return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
        }

        const setTheme = theme => {
          if (theme === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches) {
            document.documentElement.setAttribute('data-bs-theme', 'dark')
          } else {
            document.documentElement.setAttribute('data-bs-theme', theme)
          }
        }

        setTheme(getPreferredTheme())

        const showActiveTheme = (theme, focus = false) => {
          const themeSwitcher = document.querySelector('#bd-theme')

          if (!themeSwitcher) {
            return
          }

          const btnToActive = document.querySelector(`[data-bs-theme-value="${theme}"]`)

          document.querySelectorAll('[data-bs-theme-value]').forEach(element => {
            element.classList.remove('checked')
          })

          btnToActive.classList.add('checked')

          if (focus) {
            themeSwitcher.focus()
          }
        }

        window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
          const storedTheme = getStoredTheme()
          if (storedTheme !== 'light' && storedTheme !== 'dark') {
            setTheme(getPreferredTheme())
          }
        })

        window.addEventListener('DOMContentLoaded', () => {
          showActiveTheme(getPreferredTheme())

          document.querySelectorAll('[data-bs-theme-value]')
            .forEach(toggle => {
              toggle.addEventListener('click', () => {
                const theme = toggle.getAttribute('data-bs-theme-value')
                setStoredTheme(theme)
                setTheme(theme)
                showActiveTheme(theme, true)
              })
            })
        })
      })()
    </script>

字符串
我正在尝试控制按钮组:

<div class="btn-group" id="bd-theme" role="group">
    <input autocomplete="off" checked class="btn-check" data-bs-theme-value="light" id="btnradio1" name="btnradio" type="radio">
    <label class="btn btn-outline-dark" for="btnradio1">
      Light
    </label>
    <input autocomplete="off" class="btn-check" data-bs-theme-value="dark" id="btnradio2" name="btnradio" type="radio">
    <label class="btn btn-outline-dark" for="btnradio2">
      Dark
    </label>
    <input autocomplete="off" class="btn-check" data-bs-theme-value="auto" id="btnradio3" name="btnradio" type="radio">
    <label class="btn btn-outline-dark" for="btnradio3">
      Auto
    </label>
  </div>


默认情况下,“Light”模式是“选中”的,但是如果已经存储了不同的“主题”,那么其他单选按钮应该被“选中”。
我认为特别需要修改的代码是:

const showActiveTheme = (theme, focus = false) => {
          const themeSwitcher = document.querySelector('#bd-theme')

          if (!themeSwitcher) {
            return
          }

          const btnToActive = document.querySelector(`[data-bs-theme-value="${theme}"]`)

          document.querySelectorAll('[data-bs-theme-value]').forEach(element => {
            element.classList.remove('checked')
          })

          btnToActive.classList.add('checked')

          if (focus) {
            themeSwitcher.focus()
          }
        }

ecfdbz9o

ecfdbz9o1#

确定要切换的是classList吗?似乎checked只是您关心的DOMNode上的checked属性?也就是说,您只需要设置element.checked = true,而不是element.classList.add('checked')

document.getElementById('makeDark').addEventListener('click', () => {
    document.getElementById('dark').checked = true;
});

document.getElementById('makeDarkBroken').addEventListener('click', () => {
    document.getElementById('dark').classList.toggle('checked');
});
.checked {
  width: 20px;
  height: 20px;
}
<label><input id="light" name="demo" value="light" type="radio" checked /> Light</label>
<label><input id="dark" name="demo" value="dark" type="radio" /> Dark</label>

<button id="makeDark">Make Dark</button>
<button id="makeDarkBroken">Make Dark Broken</button>

相关问题