首页 > 解决方案 > 水平滚动条粘在底部

问题描述

我正在寻找粘底水平滚动条的解决方案。在视图中,有一个巨大的表格,我不想给它固定高度,所以我们会有页面级垂直滚动条,但我给定了固定宽度,所以会有一个网格级水平滚动条。

问题是我不想一直向下使用水平滚动条,我正在寻找一种解决方案来使水平滚动条粘在视图的底部。

在此处输入图像描述

标签: htmlcssscrollbarhorizontal-scrolling

解决方案


我找到了使用自定义滚动条的解决方法。在这里结帐, https://codepen.io/devashishg/pen/oNzREaw

const $scroller = document.getElementById("scroller");
const $containers = document.getElementById("container_body");
const $wrapper = document.getElementById("wrapper");
let ignoreScrollEvent = false;
animation = null;
const scrollbarPositioner = () => {
  const scrollTop = document.scrollingElement.scrollTop;
  const wrapperTop = $wrapper.offsetTop;
  const wrapperBottom = wrapperTop + $wrapper.offsetHeight;

  const topMatch = window.innerHeight + scrollTop >= wrapperTop;
  const bottomMatch = scrollTop <= wrapperBottom;

  if (topMatch && bottomMatch) {
    const inside =
      wrapperBottom >= scrollTop &&
      window.innerHeight + scrollTop <= wrapperBottom;

    if (inside) {
      $scroller.style.bottom = "0px";
    } else {
      const offset = scrollTop + window.innerHeight - wrapperBottom;

      $scroller.style.bottom = offset + "px";
    }
    $scroller.classList.add("visible");
  } else {
    $scroller.classList.remove("visible");
  }

  requestAnimationFrame(scrollbarPositioner);
};
requestAnimationFrame(scrollbarPositioner);
$scroller.addEventListener("scroll", (e) => {
  if (ignoreScrollEvent) return false;
  if (animation) cancelAnimationFrame(animation);
  animation = requestAnimationFrame(() => {
    ignoreScrollEvent = true;
    $containers.scrollLeft = $scroller.scrollLeft;
    ignoreScrollEvent = false;
  });
});
$containers.addEventListener("scroll", (e) => {
  if (ignoreScrollEvent) return false;
  if (animation) cancelAnimationFrame(animation);
  animation = requestAnimationFrame(() => {
    ignoreScrollEvent = true;
    $scroller.scrollLeft = $containers.scrollLeft;
    ignoreScrollEvent = false;
  });
});
.long {
  width: 1550px;
}

#container_body {
  overflow: hidden;
  padding-bottom: 20px;
}

#scroller {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  overflow-x: scroll;
  display: none;
}

#scroller.visible {
  display: block;
}

#scroller .long {
  height: 1px;
}
Hello<br/>
<div id="wrapper">
    <div id="container_body">
      <div class="long"> Long text</div>
      Long text
      <br />Long text
      <br />Long text
      <br />Long text
      <br />Long text
      <br />Long text
      <br />Long text
      <br />Long text
      <br />Long text
      <br />Long text
      <br />Long text
      <br />Long text
      <br />Long text
      <br />Long text
      <br />Long text
      <br />Long text
      <br />Long text
      <br />Long text
      <br />Long text
      <br />Long text
      <br />Long text
      <br />A. Long text
      <br />
    </div>
    <div id="scroller">
      <div class="long">
      </div>
    </div>
</div>
Bye

如果您有任何替代解决方案,请分享。


推荐阅读