可滚动div,仅当孩子们可以显示而不会溢出时才显示它们

时间:2018-09-07 15:51:38

标签: html css

我希望可滚动div中的子项仅在可以完整显示时才出现。

HTML

 <div id="container">
      <div class="child"></div>
      <div class="child"></div>
      <div class="child"></div>
      <div class="child"></div>
      <div class="child"></div>
      <div class="child"></div>
 </div>

CSS

 #container {
      display:block;
      overflow-y: scroll;
      overflow-x: hidden;
      height: 250px;
      width: 150px;
 }
 .child {
      background-color: red;
      height: 100px;
      width: 100px;
      margin: 5px;
 }

在此示例中,屏幕上将显示两个半红色框(第三个框使屏幕溢出,因此只有其上半部分可见)。我希望第三个(及后续)框只有在滚动时才能完整显示。

2 个答案:

答案 0 :(得分:1)

您可以添加一些javascript代码来检查内部元素的绑定矩形。然后,如果它在内部,则可以将其不透明度设置为1。

var children = document.getElementsByClassName("child");
var container = document.getElementById("container");


   for(var i = 0; i < children.length; i++)
  {
    children[i].classList.add('donotshow');
    if(children[i].getBoundingClientRect().top > container.getBoundingClientRect().top && (children[i].getBoundingClientRect().top + children[i].getBoundingClientRect().height < container.getBoundingClientRect().top + container.getBoundingClientRect().height)){
    children[i].classList.remove('donotshow');
    }
  }

container.addEventListener("scroll", function(){
  console.log("hi");
   for(var i = 0; i < children.length; i++)
  {
    children[i].classList.add('donotshow');
    if(children[i].getBoundingClientRect().top > container.getBoundingClientRect().top && (children[i].getBoundingClientRect().top + children[i].getBoundingClientRect().height < container.getBoundingClientRect().top + container.getBoundingClientRect().height)){
    children[i].classList.remove('donotshow');
    }
  }
})

https://jsfiddle.net/x8yrv6m5/18/

希望这对您有帮助!

-谢谢

答案 1 :(得分:1)

您可以使用Intersection Observer APIpolyfill for it

这是基本的工作演示:

let children = Array.from(document.querySelectorAll('.child'));

let options = {
    root: document.querySelector('#container'),
    rootMargin: '0px',
    threshold: 1.0
}

let callback = function(entries, observer) { 
        entries.forEach(entry => {
        entry.target.style.visibility = (entry.intersectionRatio == 1) ?
'visible' : 'hidden'            // the Element whose intersection with the intersection root changed.
    });
};

let observer = new IntersectionObserver(callback, options);

children.forEach(child => observer.observe(child));
 #container {
      display:block;
      overflow-y: scroll;
      overflow-x: hidden;
      height: 250px;
      width: 150px;
 }
 .child {
      background-color: red;
      height: 100px;
      width: 100px;
      margin: 5px;
 }
 <div id="container">
      <div class="child" id="child1"></div>
      <div class="child" id="child2"></div>
      <div class="child" id="child3"></div>
      <div class="child" id="child4"></div>
      <div class="child" id="child5"></div>
      <div class="child" id="child6"></div>
 </div>