Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

javascript - 如何为每个类分配不同的CSS转换值?(How to assign different css translation value per class?)

.buttons > * {
  transition: transform 700ms;
} 
.buttons > .one.closed {
  transform: translateY(-10vh);
}
.buttons > .two.closed {
  transform: translateY(-20vh);
}
.buttons > .three.closed {
  transform: translateY(-30vh);
}

I have this code, on click i add .closed class to the three elements, is there a way to achieve the same effect without writing the css rule n times?

(我有这段代码,单击后将.closed类添加到这三个元素中,有没有一种方法可以在不编写css规则n次的情况下达到相同的效果?)

I'm fine with doing it through js

(我很好用js来做)

This for example doesn't work :

(例如,这不起作用:)

  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/1cofL06p/

(JSFiddle: https ://jsfiddle.net/1cofL06p/)

  ask by Zee translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You forgot to insert translateY to the setAttribute.

(您忘了将translateY插入到setAttribute中。)

Anyhow, I think this should work:

(无论如何,我认为这应该可行:)

 function fn() { const menuElements = document.querySelectorAll(".buttons > div:not(.main)"); menuElements.forEach((el, key) => { el.style.transform = `translateY(${-20 * key}vh)`; el.classList.toggle("closed"); }); } 
 .buttons { display: flex; flex-direction: column; justify-content: center; align-items: flex-start; height: 69vh; } .buttons > * { transition: transform 700ms; } 
  <div onclick="fn()" class="buttons"> <div class="main" style="content: url('https://i.stack.imgur.com/440u9.png');"></div> <div class="stats" style="content: url('https://i.stack.imgur.com/440u9.png');"></div> <div class="settings" style="content: url('https://i.stack.imgur.com/440u9.png');" ></div> <div class="close" style="content: url('https://i.stack.imgur.com/440u9.png');"></div> </div> 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...