将 HTML 元素与 onscroll 链接,onchange 不起作用



我试图使div .progress容器更改其宽度一旦div #myContact达到100%高度,滚动

我已经尝试将HTML元素与OnScroll,Onchange或其他任何内容联系起来,但我似乎不知道有效。

    <div onscroll="scrollProgress()" id="containter" class="snap">
        <div class="progress-container"> //this containter needs to change width
          <div class="progress-bar" id="myContact"></div> //when this one reaches 100% height
    </div>
    </div>
    <script src="scroll.js"> </script>
#containter {
  width: 100%;
  height: 3000px; // original setting is 100vh, this value is just for scrolling without me pasting all the other elemnts
  scroll-behavior: smooth;
  overflow: scroll;
  scroll-snap-type: y mandatory;
}
.progress-container {
  position: fixed;
  width: 20%;
  height: 100%;
}
/* The progress bar (scroll indicator) */
.progress-bar {
  width: auto;
  background: #000;
  height: 0%;
  max-height: 100%
}
// Scroll function
  function scrollProgress() {
      var elem = document.getElementById('containter');
      var winScroll = elem.scrollTop;
      var height = elem.scrollHeight - document.documentElement.clientHeight;
      var scrolled = (winScroll / height) * 100;
      document.getElementById("myContact").style.height = scrolled + "%";
};
    // Expand function
    /* When 'myContact' reaches 100% height then 'progres-container' expands left, and cover the entire screen*/
  function expandMe() {
    let trigger = document.getElementById('myContact').style.height;
    if (trigger = 100) {
      document.getElementById('progress').style.width = trigger + "%";
    }
  };
/* When 'myContact' reaches 100% height then 'progres-container' expands left,
 and cover the entire screen*/

什么都没有发生,我也没有错误。

非常感谢!

它不是像素完美的解决方案,但是由于您的代码中有一些错误,因此,事件侦听器应绑定到window对象,因此它将根据需要呈现。我为宽度变化样式添加了一些视觉效果。

window.addEventListener('scroll', function () {
      var winScroll = window.pageYOffset;
      var height = document.getElementById('container').scrollHeight - document.documentElement.clientHeight;
      var scrolled = (winScroll / height) * 100;
      document.getElementById("myContact").style.height = scrolled + "%";
      document.getElementById("myContact").parentElement.style.width =(scrolled >= 100) ? scrolled + "%" : "20%";
});
#container {
  width: 100%;
  height: 3000px;
  scroll-behavior: smooth;
  overflow: scroll;
  scroll-snap-type: y mandatory;
}
.progress-container {
  position: fixed;
  background: #0f0;
  width: 20%;
  height: 100%;
  transition: width 1s;
}
/* The progress bar (scroll indicator) */
.progress-bar {
  width: auto;
  background: #f00;
  height: 0%;
  max-height: 100%
}
<div id="container" class="snap">
        <div class="progress-container"> 
          <div class="progress-bar" id="myContact"></div>
    </div>
</div>

最新更新