【问题标题】:Using jQuery and CSS3's TranslateX() to reveal an element while scrolling parent element into view使用 jQuery 和 CSS3 的 TranslateX() 在将父元素滚动到视图中时显示元素
【发布时间】:2019-09-13 01:01:43
【问题描述】:

当它的父部分滚动到视图中时,我想更改圆的位置。

在父项出现后向下滚动时,它应该向右移动,当向上滚动时,它应该回到原来的位置。 (向左-200px)它只能在用户主动滚动时移动。

如果用户一直向下滚动到圆圈父部分的最底部,或者如果他们已经向下滚动到底部并重新加载页面,则圆圈应该出现在完全显示的位置。

我当前的代码部分有效,但是我无法根据父元素的可见程度来显示整个元素,并且在滚动到页面后重新加载页面时也无法使其显示在最终位置最底层。

JSFiddle:https://jsfiddle.net/thebluehorse/gu2rvnsw/

var $window = $(window),
    $sectionFour = $('.section-four'),
    $circle = $sectionFour.find('.circle'),
    lastScrollTop = 0,
    position = -200;

function revealCircle() {
  var isVisible,
  	st = $window.scrollTop();

  isVisible = isInView($sectionFour);

  if (isVisible) {
    // console.log('section four is in view, so lets do stuff!');

    if (st > lastScrollTop) {
      if (position === 0) {
        return false
      }
      $circle.css('transform', 'translateX(' + position + 'px')
      position++;
    } else {
      if (position === -200) {
        return false
      }
      $circle.css('transform', 'translateX(' + position + 'px')
      position--;
    }
  }
}

function isInView(node) {
  var rect;

  if (typeof jQuery === 'function' && node instanceof jQuery) {
    node = node[0];
  }

  rect = node.getBoundingClientRect();

  return (
    (rect.height > 0 || rect.width > 0) &&
    rect.bottom >= 0 &&
    rect.right >= 0 &&
    rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
    rect.left <= (window.innerWidth || document.documentElement.clientWidth)
  );
}

$window.on('scroll', revealCircle);
.circle {
  width: 400px;
  height: 400px;
  background: #fff;
  -webkit-border-radius: 200px;
  -moz-border-radius: 200px;
  border-radius: 200px;
  transform: translateX(-200px); }

.section {
  min-height: 400px; }
  .section-one {
    background-color: red; }
  .section-two {
    background-color: orange; }
  .section-three {
    background-color: yellow; }
  .section-four {
    background-color: green; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="section section-one"></section>
<section class="section section-two"></section>
<section class="section section-three"></section>
<section class="section section-four">
  <div class="circle"></div>
</section>

【问题讨论】:

    标签: javascript jquery css scroll transform


    【解决方案1】:

    您的代码可以简化一点。当页面滚动时,您需要跟踪的唯一值是scrollTop()。因为$sectionFour 的几何形状永远不会改变,所以您可以立即缓存它的getBoundingClientRect()。

    一旦您知道$sectionFour 在视图中,您就想知道它的总高度中有多少像素在视图中,将其转换为百分比,然后将该百分比应用于初始位置 -200。本质上,当只显示几个像素时,这是一个很小的百分比,例如 10% 和 -200 变为 -180。当元素完全在视图中时,百分比应该接近 100%,并且 -200 变为 0。这意味着您没有跟踪最后一个位置或滚动的方向,您只是在计算值应该是什么基于当前视口(scrollTop)。

    var $window = $(window),
      $sectionFour = $('.section-four'),
      $circle = $sectionFour.find('.circle');
      rect = $sectionFour[0].getBoundingClientRect();
    
    function revealCircle() {
      var scrollTop = $window.scrollTop();
      var windowHeight = $window[0].innerHeight;
    
      if (scrollTop + windowHeight > rect.top) {    
        var percentVisible = (scrollTop - (rect.top - windowHeight)) / rect.height;
        var position = 200 - (percentVisible * 200);
        
        $circle.css('transform', 'translateX(-' + position + 'px');
      }
    }
    
    $window.on('scroll', revealCircle);
    body { margin:0;}
    
    .circle {
      width: 400px;
      height: 400px;
      background: #fff;
      -webkit-border-radius: 200px;
      -moz-border-radius: 200px;
      border-radius: 200px;
      transform: translateX(-200px); }
    
    .section {
      min-height: 400px; }
      .section-one {
        background-color: red; }
      .section-two {
        background-color: orange; }
      .section-three {
        background-color: yellow; }
      .section-four {
        background-color: green; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <section class="section section-one"></section>
    <section class="section section-two"></section>
    <section class="section section-three"></section>
    <section class="section section-four">
      <div class="circle"></div>
    </section>

    【讨论】:

    • 感谢您的帮助!这看起来不错,但是,在滚动到页面底部,然后重新加载页面后,圆圈出现在屏幕外 -200px 而不是 0。任何想法如何解决?我尝试将“加载”添加到窗口 on() 事件侦听器,但没有帮助。
    • 您可能没有在加载事件中缓存所有变量。只需在 JS 的最后一行直接调用 revealCircle()。
    【解决方案2】:

    在纯 JS 解决方案中使用 css 变量可能更简单:

    const sectFour  = document.querySelector('#section-four')
        , divCircle = sectFour.querySelector('.circle')
    
    
    function percentVisible(elm)
      {
      let rect       = elm.getBoundingClientRect()
        , viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight)
        , visu       = viewHeight-rect.top
    
      return (visu<0) ? -1 : Math.min( 100, (visu/rect.height*100))
      // return !(rect.bottom < 0 || rect.top - viewHeight >= 0)  =>  checkVisible
      }
    
    window.onscroll=_=>
      {
      let circlePos = percentVisible(sectFour) *2
    
      if (circlePos>=0)
        {
        divCircle.style.setProperty('--circle-pos', `-${200-circlePos}px`)
        // IE 11 : // divCircle.style=('transform:translateX(-'+(200-circlePos)+'px')
        }
      }
    * { margin: 0 }
    
    .circle {
      --circle-pos         :-200px;
      width                : 400px;
      height               : 400px;
      background-color     : #fff;
      -webkit-border-radius: 200px;
         -moz-border-radius: 200px;
              border-radius: 200px;
      transform            : translateX(var(--circle-pos));
      /* IE 11 ........... : translateX(-200px); */
    }
    
    section { min-height: 400px;  }
    section:nth-of-type(1) { background-color: red;    }
    section:nth-of-type(2) { background-color: orange; }
    section:nth-of-type(3) { background-color: yellow; }
    section:nth-of-type(4) { background-color: green;  }
    <section></section>
    <section></section>
    <section></section>
    <section id="section-four"> <div class="circle"></div> </section>

    【讨论】:

    • 这是一个很好的解决方案,但是,我需要它在 IE 11 中工作。你有解决这个问题的方法吗?
    • @Cofey :没有css变量你可以使用:divCircle.style=('transform:translateX(-'+(200-circlePos)+'px')
    【解决方案3】:

    你应该看看Intersection Observer (IO),这是为了解决像你这样的问题。监听滚动事件并计算位置可能会导致性能下降。

    首先,您必须定义 IO 的选项:

    let options = {
      root: document.querySelectorAll('.section-four'),
      rootMargin: '0px',
      threshold: 1.0
    }
    
    let observer = new IntersectionObserver(callback, options);
    

    在定义选项后,您必须告诉观察者要观察哪些元素,我猜在您的情况下这将是.section-four:

    let targets = document.querySelectorAll('.section-four');
    targets.forEach(target => {
      observer.observe(target) } 
    )
    

    最后一步是定义一旦.section-four 进入视野就应该执行的回调函数:

    let callback = (entries, observer) => { 
      entries.forEach(entry => {
        // Each entry describes an intersection change for one observed
        // target element
        // here you can do something like $(entry.target).find('circle') to get your circle
      });
    };
    

    查看this demo,这取决于元素可见的背景颜色变化程度。我认为这与您的问题很接近,您只是不更改为元素内的圆圈设置动画的背景颜色。

    网站上还有另一个演示,它显示了一个元素在屏幕上可见的程度,也许这更适合你。

    您也可以使用此polyfill from w3c 来支持旧版浏览器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      • 2011-06-20
      • 1970-01-01
      • 2016-11-01
      相关资源
      最近更新 更多