繁体   English   中英

在滚动条上显示每个部分的元素,jQuery

[英]Displaying each section's elements on scroll, jQuery

我有opacity: 0部分内的元素。 并试图使opacity: 1如果他们的部分在 window 中完全可见。 我写的代码如下。 它有缺陷。

 $(window).scroll( function(){ $('.parts').each(function(i){ var sectionBottom = $(this).position().top + $(this).outerHeight(); var windowBottom = $(window).scrollTop() + $(window).height(); if( windowBottom > (sectionBottom + 300) ){ $("h1").css("opacity", "1"); $("h2").css("opacity", "1"); $("h3").css("opacity", "1"); } }); });
 .parts { height: 100vh; display: flex; align-items: center; justify-content: center; }.part1 { background-color: yellow; }.part2 { background-color: red; }.part3 { background-color: blue; } h1,h2,h3 { text-align: center; color: #000; opacity: 0; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <section class="parts part1"> <h1>this is the el of 1</h1> </section> <section class="parts part2"> <h2>this is the el of 1</h2> </section> <section class="parts part3"> <h3>this is the el of 1</h3> </section>

它同时显示所有元素。 如何使元素仅显示其在 window 中可见的部分。

卷轴 function 中有一个小问题。 滚动 function 只是检查windowBottom > (sectionBottom + 300)如果它是真的,它只会使其他部分的所有内容也可见。

要在滚动时解决此问题,请检查该部分是否在 window 中可见,然后使其中的元素可见( opacity: 1 )。

$(window).scroll(function() {
  $('.parts').each(function(i, ele) {
    console.log(isElemIntoView(ele));
    console.log();
    if (isElemIntoView(ele)) {
      $(ele.className + " *").css("opacity", "1");
    }
  });
});


function isElemIntoView(elem) {
  var docViewTop = $(window).scrollTop();
  var docViewBottom = docViewTop + $(window).height();

  var elemTop = $(elem).offset().top;
  var elemBottom = elemTop + $(elem).height();

  return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

 sectionDisplay(); $(window).scroll(function() { sectionDisplay(); }); function sectionDisplay() { $('.parts').each(function(i) { if ($(this).position().top - 100 <= $(window).scrollTop()) { $(this).children().animate({ opacity: 1 }); } }); }
 .parts { height: 100vh; display: flex; align-items: center; justify-content: center; }.part1 { background-color: yellow; }.part2 { background-color: red; }.part3 { background-color: blue; } h1, h2, h3 { text-align: center; color: #000; opacity: 0; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <section class="parts part1"> <h1>this is the el of 1</h1> </section> <section class="parts part2"> <h2>this is the el of 1</h2> </section> <section class="parts part3"> <h3>this is the el of 1</h3> </section> <section class="parts part1"> <h1>this is the el of 1</h1> </section> <section class="parts part2"> <h2>this is the el of 1</h2> </section>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM