【问题标题】:Adding Scroll Transition using Javascript使用 Javascript 添加滚动过渡
【发布时间】:2022-11-26 15:09:28
【问题描述】:

我正在使用 javascript 在一次滚动后隐藏图像。代码工作正常,但我无法向它添加任何过渡,因为它有一种非常不稳定和粗糙的感觉。

这是我正在使用的代码


function runOnScroll() {
    if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
      document.getElementById("logoimg-hidden").style.maxWidth = "0";    
       document.getElementById("logoimg-hidden").style.transition = "max-width .4s linear"
      }
  else{
     document.getElementById("logoimg-hidden").style.maxWidth = "inherit";
    document.getElementById("logoimg-hidden").style.transition = "max-width .4s linear"
  }
 }; 
window.addEventListener("scroll", runOnScroll);

过渡不起作用。如果我能得到一个在滚动上添加过渡的解决方案,我将非常感激。谢谢!

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    尝试通过 CSS 而不是通过 JS 设置过渡属性。

    #logoimg-hidden {
        .
        .
        .
        transition: max-width 0.4s linear;
    }
    

    【讨论】:

      【解决方案2】:

      inherit 用于 max-width 似乎是问题所在。尝试用 px% 等度量单位给它一个值。

      function runOnScroll() {
        if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
            document.getElementById("logoimg-hidden").style.maxWidth = "0";    
        } else{
           document.getElementById("logoimg-hidden").style.maxWidth = "100%";
        }
      }
      window.addEventListener("scroll", runOnScroll);
      div {
        height: 400vh;
      }
      
      #logoimg-hidden {
        padding: 20px;
        background-color: #555;
        transition: max-width .4s linear;
      }
      <div>
        <div id="logoimg-hidden">image</div>
      </div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-03-29
        • 2016-06-13
        • 2014-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多