首页 > 解决方案 > 使用javascript滚动时隐藏右边框

问题描述

在此处输入图像描述

我想在垂直滚动时隐藏边框。请帮忙。

   
           

标签: javascriptcss

解决方案


您可以像这样实现该功能。

脚步

  1. 选择容器或 div。
  2. 并创建一个函数,不断检查div的scrollHeight是否大于clientHeight,如果滚动高度大于客户端高度,则表示有滚动条。
  3. 并使用 ResizeObserver 观察高度变化 doc 链接https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver

注意:尝试调整窗口大小以查看效果或调整高度。

// selecting the div
const myDiv = document.querySelector('.my-div');

// checking should remove the border or add
const shouldRemoveBorder = () => {
 const hasVerticalScrollbar= myDiv.scrollHeight>myDiv.clientHeight;

if(hasVerticalScrollbar) {
  myDiv.style.borderRight = "none"
} else {
   myDiv.style.borderRight = "1px solid"
  }   
}

new ResizeObserver(shouldRemoveBorder).observe(myDiv)
.my-div {
  width: 60%;
  padding: 10px 20px;
  height: 150px;
  background: yellow;
  overflow-y: auto;
}
<div class="my-div">
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>


推荐阅读