簡體   English   中英

在選中的單選按鈕和復選框按鈕上觸發動畫

[英]Trigger animation on checked radio and checkbox buttons

我想在選擇radiocheckbox按鈕時動畫更改body背景顏色。

我知道如何處理單個輸入:

JavaScript:

const apples = document.querySelector("#apples")

apples.addEventListener("change", function() {
  if(this.checked) {
    document.body.style.animation = "switch 1s ease-in-out"
  }     
})

然后在 CSS 中:

@keyframes switch {
  to {
    background: red
  }
}

HTML:

<form>
  <fieldset>
    <label><input type="checkbox" name="foo" id="apples">Apples</label>
    <label><input type="checkbox" name="foo" id="bananas">Bananas</label>
  </fieldset>
  <fieldset>
    <label><input type="radio" name="bar" id="juice">Juice</label>
    <label><input type="radio" name="bar" id="lemonade">Lemonade</label>
  </fieldset>
</form>

但是,如果我有一個顏色與inputid配對的對象,我該如何使用 vanilla JavaScript 做到這一點?

const accentColors = {
  apples: "red",
  bananas: "yellow",
  juice: "green",
  lemonade: "yellow"
}

我不確定這是最佳實踐,但我讀過創建動態@keyframes一種方法是注入使用 js 創建的動態 css。

 const accentColors = { apples: "red", bananas: "yellow", juice: "green", lemonade: "yellow" } let keyFrameStylesToInject = ''; // Create the styles and add event listeners Object.keys(accentColors).forEach(k => { keyFrameStylesToInject += `@keyframes switch-${k} {to {background: ${accentColors[k]}}}`; document.querySelector(`#${k}`).addEventListener('change', function(){ if(this.checked) { document.body.style.animation = `switch-${k} 1s ease-in-out`; } else { document.body.style.animation = undefined; } }); }); // Inject the css const style = document.createElement('style'); style.type = 'text/css'; style.innerHTML = keyFrameStylesToInject; document.head.appendChild(style);
 <form> <fieldset> <label><input type="checkbox" name="foo" id="apples">Apples</label> <label><input type="checkbox" name="foo" id="bananas">Bananas</label> </fieldset> <fieldset> <label><input type="radio" name="bar" id="juice">Juice</label> <label><input type="radio" name="bar" id="lemonade">Lemonade</label> </fieldset> </form>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM