【问题标题】:when adding a class, styles are applied without smooth transition添加类时,应用样式而不平滑过渡
【发布时间】:2019-08-10 00:39:50
【问题描述】:

我希望一个元素在 2 秒后以流畅的方式应用一些样式。我尝试了 setTimeout,在两秒后添加该类,但尽管已将 transition: all 1s 声明为绝对所有内容,但当添加该类(包含新样式)时,我看不到任何“过渡”,新样式只是应用没有平滑度。

我该如何解决?

var s2 = document.querySelector("#section2");
setTimeout(() => {
  s2.classList.add("up");
}, 2000);
html * {
  transition: 1s all;
}

body {
  overflow: hidden;
}

#section1 {
  background: steelblue;
}

#section2 {
  background: indigo;
  position: absolute;
}

section {
  width: 100%;
  height: 100vh;
}

.up {
  top: 0px;
}
<section id="section1"></section>
<section id="section2"></section>

我想要实现的是,第一个下方的 div 开始向上移动,直到到达窗口顶部,就像“向上滑动”效果一样。为什么在添加包含这种新样式的类后会忽略“过渡”属性?

【问题讨论】:

标签: css


【解决方案1】:

您需要为top 规则应用一个初始值以使转换生效。

var s2 = document.querySelector("#section2");
setTimeout(() => {
  s2.classList.add("up");
}, 2000);
html * {
  transition: 1s all;
}

body {
  overflow: hidden;
  position: relative; /** ensure section#section2 is positioned relative to the body **/
}

#section1 {
  background: steelblue;
}

#section2 {
  background: indigo;
  position: absolute;
  top: 100vh; /** initial value **/
}

section {
  width: 100%;
  height: 100vh;
}

/** #section2.up is more specific **/
#section2.up {
  top: 0;
}
<section id="section1"></section>
<section id="section2"></section>

【讨论】:

    【解决方案2】:

    您还可以使用 jQuery 等外部库进行动画处理:

    $("#section2").animate({
      top: 0,
      duration: 2000
    });
    html * {
      transition: 1s all;
    }
    
    body {
      overflow: hidden;
    }
    
    #section1 {
      background: steelblue;
    }
    
    #section2 {
      background: indigo;
      position: absolute;
    }
    
    section {
      width: 100%;
      height: 100vh;
    }
    <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
    
    <section id="section1"></section>
    <section id="section2"></section>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-20
      • 2020-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多