首页 > 解决方案 > Pure(Vanilla) Javascipt 同步设置过渡和样式,它没有按我想要的方式表现

问题描述

正如我下面的代码

  1. 我点击btn-01,bg-01 opacity从0到1,左从0到300px(1200ms)
  2. 然后我点击btn-02,bg-01需要从不透明度0.3到1,从150px到450px(1200ms)

let bg = document.querySelector(".bg-01")

document.querySelector(".btn-01").addEventListener("click",function(){
  bg.style.transitionDuration = "1200ms"
  bg.style.left = "300px"
  bg.style.opacity = "1"
})
document.querySelector(".btn-02").addEventListener("click",function(){
  bg.style.transitionDuration = "0ms"
  bg.style.left = "150px"
  bg.style.opacity = "0.3"
  // setTimeout(()=>{
    bg.style.transitionDuration = "1200ms"
    bg.style.left = "450px"
    bg.style.opacity = "1"
  // },10)
  
})
.bg-01 {
  width: 100px;
  height: 100px;
  background-color: red;
  position: relative;
}
<button type"button" class="btn-01">001</button>
<button type"button" class="btn-02">002</button>

<div class="bg-01" style="opacity:0; left:0;">
  
</div>

但它并没有像我想要的那样表现。

在第 2 步中,当单击 btn-02 时,bg-01 只需移动:从 300px 向左移动到 450px。

在我的逻辑中:由于持续时间设置为“0ms”,bg-01突然转到左侧:150px(不透明度),然后持续时间设置为“1200ms”,然后bg-01转到左侧:450px

但它只是直接从 300px 移动到 450px ......

为什么会这样???

我只是通过添加 setTimeout 来解决这个问题。

它有什么办法可以解决这个问题吗?

标签: javascripthtmlcssstylescss-transitions

解决方案


推荐阅读