当用户使用jQuery滚动时,在另一个div中触发滚动事件

Jim*_*mmy 8 html javascript jquery

我有两个div元素:

当用户滚动div #element-A#header-one-target到达包含div的顶部时,其中的最后一个元素(#animate-hd-b#element-B应滚动到包含div的顶部,并带有漂亮的动画。

这是我要开始使用的代码。下面的代码在滚动窗口而不是div时会执行某些操作。

$(window).scroll(function() {

  var offsetTop = $('#animate-hd-b').offset().top,
    outerHeight = $('#animate-hd-b').outerHeight(),
    windowHeight = $(window).height(),
    scrollTop = $(this).scrollTop();

  console.log((offsetTop-windowHeight) , scrollTop);

  if (scrollTop > (offsetTop+outerHeight-windowHeight)){
    alert('you have scrolled to the top!');
  }
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="element-A" style="background: orange; overflow: auto;">
  <div class="content" style="padding-bottom: 300px;">
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <h1 id="header-one-target">Header One</h1>
  </div>
</div>

<div id="element-B" style="background: yellow; overflow: auto;">
  <div class="content" style="padding-bottom: 300px;">
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <h1 id="animate-hd-b">Animate This Header</h1>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

有没有办法在jQuery中做到这一点?

Mun*_*nna 4

这真的很简单。您只需在到达顶部时进行跟踪#header-one-target并制作动画 即可。#animate-hd-b#header-one-target

(function($) {
  let $elementA = $('#element-A');
  let $elementB = $('#element-B');
  let $headerOneTarget = $('#header-one-target');
  let $animateHdB = $('#animate-hd-b');
  let isScrollAtTop = true;
  $elementA.scroll(function() {
    if (isScrollAtTop && $headerOneTarget.offset().top < 5) {
      isScrollAtTop = false;
      $elementB.animate({
        scrollTop: $elementB.scrollTop() + $animateHdB.offset().top
      });
    } else if ($elementA.scrollTop() < 5) {
      isScrollAtTop = true;
      $elementB.animate({
        scrollTop: 0
      });
    }
  });
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
#element-A {
  background: orange;
  overflow: auto;
  height: 100vh;
  width: 60vw;
  position: fixed;
  top: 0;
  left: 0;
}

#element-B {
  position: fixed;
  top: 0;
  right: 0;
  height: 100vh;
  width: 40vw;
  background: yellow;
  overflow: auto;
}

.content {
  padding: 10px;
}

.content-vh100 {
  height: 100vh;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="element-A">
  <div class="content">
    <p>Scroll</p>
    <p>to</p>
    <p>header</p>
    <p>one</p>
    <h1 id="header-one-target">Header One</h1>
    <div class="content-vh100"></div>
  </div>
</div>

<div id="element-B">
  <div class="content">
    <p>to</p>
    <p>animate</p>
    <p>following</p>
    <p>content</p>
    <h1 id="animate-hd-b">Animate This Header</h1>
    <div class="content-vh100"></div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)