当选择body
或radio
按钮时,我想为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
答案 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>