【问题标题】:Is there any way to change a div size on scroll using intersectionObserver?有没有办法使用intersectionObserver 更改滚动时的div 大小?
【发布时间】:2019-10-10 21:54:49
【问题描述】:

我正在尝试在滚动时更改 div 的大小(或比例)。 这个 div 有一个 0.8 的比例附在它的 css 上。我想在滚动时逐渐达到 1 的比例。 IntersectionObserver 似乎是一个不错的选择,而不是滚动事件,但我不知道我是否可以使用它来更改元素的状态。

【问题讨论】:

    标签: javascript scroll intersection-observer


    【解决方案1】:

    您可以使用更改 div 的比例。

    document.getElementById("scaledDiv").style.transform = "scale(1)";
    

    滚动事件应该做你想做的事。您可以继续添加更多 if 语句并检查它们滚动了多少像素,以便在它们向上滚动时逐渐将其更改为 1 甚至回到 0.8。下面的 50 代表距离页面顶部 50 个像素。

    window.onscroll = function() {
        if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
            // They are scrolling past a certain position
    
            document.getElementById("scaledDiv").style.transform = "scale(1)";
    
        } else {
            // They are scrolling back
    
        }
    };
    
    

    【讨论】:

    • 感谢您的快速回答,但我正在尝试让它在滚动时动态更改
    • 你可以通过 onscroll 事件来做到这一点。添加更多 if 语句并检查它们在页面上滚动的距离。随着它们继续滚动,您可以逐渐改变比例。
    【解决方案2】:

    希望对你有帮助:

    const container = document.querySelector('.container');
    const containerHeight = container.scrollHeight;
    const iWillExpand = document.querySelector('.iWillExpand');
    
    container.onscroll = function(e) {
      iWillExpand.style.transform = `scale(${0.8 + 0.2 * container.scrollTop / (containerHeight - 300)})`;
    };
    .container {
      height: 300px;
      width: 100%;
      overflow-y: scroll;
    }
    .scrollMe {
      height: 1500px;
      width: 100%;
    }
    
    .iWillExpand {
      position: fixed;
      width: 200px;
      height: 200px;
      top: 10px;
      left: 10px;
      background-color: aqua;
      transform: scale(0.8);
    }
    <div class='container'>
      <div class='scrollMe' />
      <div class='iWillExpand' />
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-29
      • 1970-01-01
      • 2017-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-30
      • 2016-02-18
      相关资源
      最近更新 更多