提问者:小点点

使用vanilla JavaScript滚动时显示div


我使用的是vanilla JavaScript,我想找出一种隐藏div容器的方法,但是当用户滚动到div容器的50%时,就是div完全可见的时候。有点像渐变效应。这是我目前所掌握的:

null

// delays scroll affects
function debounce(func, wait = 20, immediate = true) {
  var timeout;
  return function() {
    var context = this,
      args = arguments;
    var later = function() {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };
    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(context, args);
  };
}

// adds animation for section cards 
function cardActive(e) {
  const cards = document.querySelectorAll('.slide-in');
  // checks if image is half shown from bottom
  cards.forEach(card => {
    const slideInAt = (window.scrollY + window.innerHeight) - card.height / 2;
    if (slideInAt > card.offsetTop) {
      card.classList.add('active')
    } else {
      card.classList.remove('active');
    }
  })
};

window.addEventListener('scroll', debounce(cardActive));
.slide-in {
  opacity: 50%;
  transition: opacity 0.8s;
}

.slide-in.active {
  transition: opacity 0.8s;
  opacity: 100%;
  visibility: visible !important;
}

.placeholder {
  margin-top: 400px;
}

.icon {
  width: 100px;
}
<div class="placeholder"></div>

<div class="mission-1 slide-in">
  <div class="section-card">
    <img class="icon" src="https://image.flaticon.com/icons/svg/869/869767.svg" alt="icon">
    <h6 class="mission-card-title">Title 1</h6>
    <p class="p-special">Lorem Ipsum.</p>
  </div>
</div>

<div class="placeholder"></div>

null


共1个答案

匿名用户

你需要做两个小小的改变:

>

  • 您需要将JS文件中的Card.height替换为Card.offsetheight

    在CSS文件中使用转换,您不需要动画来使渐变生效:

    .slide-in {
       opacity: 0%;
       transition: opacity 0.8s;
    }
    
    .active {
       transition: opacity 0.8s;
       opacity: 100%;
       visibility: visible !important;
    }