【问题标题】:Stacking multiple Transformations of the same Type in Css在 Css 中堆叠多个相同类型的转换
【发布时间】:2020-08-21 22:16:33
【问题描述】:

我想要一些针对相同属性的转换相互堆叠。

以下面的示例为例:如果多次单击按钮,效果应该会累加。然后,该框也会根据点击频率更快地向右移动。

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>

【问题讨论】:

  • 简单设置margin-left
  • 但这就是我所做的,对吧?
  • 你把它设置为100px,没有增加它。
  • 是的 :) 我将如何增加它?
  • 我已经给出了答案。你可以直接在javascript中设置样式。

标签: javascript html css css-transitions


【解决方案1】:

你可以通过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>

【讨论】:

  • 太棒了。肯定学到了新东西。我试试看
  • 这不是一个也适用于框架的解决方案,是吗?我正在使用 react,我希望该问题的一般解决方案也可能适用
  • @Tobi 这是纯粹的 js,应该总是可以工作,如果任何框架破坏了它,修复它是他们的问题(我相信 react 允许你设置像 this random search result 这样的属性)。
  • @Tobi 请注意,react 或多或少地做了我所展示的事情,因此它会与我的代码(以及许多本机方法)发生冲突。
  • 我只需使用style = { ... } 以及将过渡移动到普通类就可以了
【解决方案2】:

也许你可以在你的函数中传递一个速度参数并在你的 css 中使用它,而不是使用静态值,或者每次点击都会增加它。

【讨论】:

  • 如何将值传递给我的 css 样式表?这也是一个问题。我可以使用内联样式,但它认为它可以堆叠起来
  • 您可以为此使用 css 变量。请参考developer.mozilla.org/en-US/docs/Web/CSS/…
猜你喜欢
  • 1970-01-01
  • 2018-11-17
  • 2014-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多