【问题标题】:CSS incrementing transition animation on every button click每次单击按钮时 CSS 递增过渡动画
【发布时间】:2021-09-26 18:36:28
【问题描述】:

给定

var box = document.querySelector('.box');

document.addEventListener("click", (event) => {
  if (!event.target.closest("button")) return;
  
  if(event.target.id === "button") {
    box.classList.add('move');
  } 
    
});
.box {
    width: 100px;
    height: 100px;
    background-color: #000;
    transition: transform 1s;
}

.move {
    transform: translateX(20px);
}
<div class="box"></div>
<button id="button">button</button>

使用 JS Fiddle here.

我希望框的 x 位置在每次单击按钮时增加 20px


我不确定如何继续。我最初尝试使用@KeyForms,但这需要fromto 前缀,我不能(我认为)在其上添加变量值。这里出现了同样的问题,似乎我不能在 css 代码中有一个可以递增的变量。我是否使用了正确的功能(transition)?

我也试过

if(event.target.id === "button") {
    if(!box.classList.contains('open')){
        box.classList.add('open');
    }else {
        box.classList.remove('open');
    }
  }

但这似乎会反复来回移动盒子。

有没有人有任何提示或想法? (我正在添加Javascript标签,因为我怀疑这个问题可能直接在JS中解决)。

【问题讨论】:

  • 在 JS 中玩 animate 很有趣 :)

标签: javascript css css-transitions css-transforms


【解决方案1】:

您可以将x 位置存储在一个变量中,每次点击增加20 并将其应用于transform 样式属性:

var x = 0, box = document.querySelector('.box');
button.addEventListener('click', function() {
  x += 20, box.style.transform = `translateX(${x}px)`;
})
.box {
  width: 100px;
  height: 100px;
  background-color: #000;
  transition: 1s;
}
<div class="box"></div>
<button id="button">button</button>

【讨论】:

  • 糟糕,抱歉!
【解决方案2】:

继续添加使用 javascript 样式

var button = document.querySelector('#button');

button.onclick = function () {
          document.querySelector('.box').style.transform += "translateX(20px)";
    };
.box {
    width: 100px;
    height: 100px;
    background-color: #000;
    transition: transform 1s;
}
<div class="box"></div>
<button id="button">button</button>

【讨论】:

    【解决方案3】:

    使用 javascript 样式可以回答您的问题。 javascript 有 CSS 样式,例如 box.style.transform = 'translateX(20px)'。在 Javascript 中,您可以计算样式值(当然在 CSS 中可以通过计算更改值)。所以我添加了一些如下代码。

    var box = document.querySelector('.box');
    let cnt = 0;
    document.addEventListener("click", (event) => {
      if (!event.target.closest("button")) return;
      
      if(event.target.id === "button") {
      console.log(box.style.transform)
        cnt++;
        console.log(cnt)
        box.style.transform = `translateX(${20 * cnt}px)`;
      } 
        
    });
    .box {
        width: 100px;
        height: 100px;
        background-color: #000;
        transition: transform 1s;
    }
    
    .move {
        transform: translateX(20px);
    }
    
    .move1 {
        transform: translateX(-20px);
    }
    <div class="box"></div>
    <button id="button">button</button>

    【讨论】:

      猜你喜欢
      • 2016-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-24
      相关资源
      最近更新 更多