猿问

使用 jQuery 和 CSS3 的 TranslateX() 在将父元素滚动到视图中时显示元素

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


在父视图中向下滚动时,它应该向右移动,向上滚动时,它应该移回原来的位置。(向左 -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; }



莫回无
浏览 480回答 3
3回答

慕桂英4014372

您应该看看Intersection Observer (IO),它旨在解决像您这样的问题。侦听滚动事件并计算位置可能会导致性能不佳。首先,您必须定义 IO 的选项:let options = {&nbsp; root: document.querySelectorAll('.section-four'),&nbsp; rootMargin: '0px',&nbsp; threshold: 1.0}let observer = new IntersectionObserver(callback, options);定义选项后,您必须告诉观察者要观察哪些元素,我想在您的情况下这将是.section-four:let targets = document.querySelectorAll('.section-four');targets.forEach(target => {&nbsp; observer.observe(target) }&nbsp;)最后一步是定义一旦.section-four进入视图就应该执行的回调函数:let callback = (entries, observer) => {&nbsp;&nbsp; entries.forEach(entry => {&nbsp; &nbsp; // Each entry describes an intersection change for one observed&nbsp; &nbsp; // target element&nbsp; &nbsp; // here you can do something like $(entry.target).find('circle') to get your circle&nbsp; });};看看这个演示,根据元素可见的程度,背景颜色会发生变化。我认为这与您的问题很接近,您只是不更改为元素内的圆圈设置动画的 bg 颜色。站点上还有另一个演示,显示屏幕上可见元素的数量,也许这更适合您。您还可以使用w3c 的这个polyfill来支持旧浏览器。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答