在CSS中堆叠相同类型的多个转换

问题描述

我希望所有针对同一个属性的转换相互叠加。

以下面的示例为例:如果多次单击该按钮,则效果应累加。然后,该框还应该根据点击次数向右移。

const clickHandler = () => {Box.classList.add("move-Box");}
.Box{
width: 50px;
padding: 10px;
margin-top: 50px;
border: 1px solid black;
}

.move-Box {
margin-left: 100px;
transition: margin-left 0.5s linear;
}
<button onclick="clickHandler()">Go over there</button>
<div id="Box" class="Box">Alright</div>

解决方法

也许您可以在函数中传递速度参数,然后在css中使用它,而不是使用静态值,或者每次单击都会增加它。

,

您可以通过javascript动态设置css值

(注意:您应该将transition: margin-left 0.5s linear;放在.box中)

const clickHandler = () => {
  const left = +box.dataset.left
  box.style.marginLeft = left + "px";
  box.dataset.left = left + 100;
}
.box {
  width: 50px;
  padding: 10px;
  margin-top: 50px;
  border: 1px solid black;
  transition: margin-left 0.5s linear;
}
<button onclick="clickHandler()">Go over there</button>
<div id="box" class="box" data-left=100>Alright</div>