.buttons > * {
transition: transform 700ms;
}
.buttons > .one.closed {
transform: translateY(-10vh);
}
.buttons > .two.closed {
transform: translateY(-20vh);
}
.buttons > .three.closed {
transform: translateY(-30vh);
}
我有此代码,单击后我将.closed类添加到这三个元素中,有没有一种方法可以在不编写css规则n次的情况下达到相同的效果?我可以通过js来做到这一点
例如,这不起作用:
const menuElements = document.querySelectorAll(".buttons > :not(.main)");
menuElements.forEach((el, key) => {
el.setAttribute("transform", -10 * key + "vh");
el.classList.toggle("closed");
});
JSFiddle:https://jsfiddle.net/ru1w5b9m/1/
您忘了将transformY插入到setAttribute中。无论如何,我认为这应该可行:
const menuElements = document.querySelectorAll(".buttons > :not(.main)");
menuElements.forEach((el, key) => {
el.style.transform = `translateY(${-10 * key}vh)`;
el.classList.toggle("closed");
});