在选中的单选和复选框按钮上触发动画

时间:2019-01-08 09:10:22

标签: javascript css css-animations

当选择bodyradio按钮时,我想为checkbox背景颜色的变化制作动画。

我知道如何输入一个信息:

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>

但是如果我有一个对象的颜色与id的{​​{1}}配对,该如何使用普通JavaScript?

input

1 个答案:

答案 0 :(得分:1)

我不确定这是否是最佳实践,但我已经读过一种创建动态@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>