4

我在使用 GSAP 的 ScrollTrigger 时遇到问题。

我将固定元素的高度设置为不同的视口宽度,并且在调整窗口大小时效果很好。

但是现在我想通过单击按钮来更改固定元素的高度。我使用ScrollTrigger.refresh();但没有任何反应。

有人可以告诉我如何解决吗?

ScrollTrigger.create({
  trigger: '.box',
  pin: true,
  start: 'top center',
  end: () => `+=${$('.h-500').height() - $('.box').height()}`,
  markers: true,
  id: "box",
  onRefreshInit: () => {
  },
  onRefresh: () => {
  }
});

function resizeBox(){
  $('.box').css('height', '50px');
  ScrollTrigger.refresh();
}
body{
  margin: 0;
}
.space {
  width: 100%;
}
.h-500 {
  height: 500px;
  background: yellow;
}
.h-1000 {
  height: 1000px;
}
.box {
  width: 100px;
  height: 100px;
  background: red;
}
button {
  position: fixed;
  top: 0;
  right: 0;
  z-index: 999;
  font-size: 20px;
}

@media only screen and (max-width: 600px) {
  .box {
    height: 5vw;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/gsap@3/dist/ScrollTrigger.min.js"></script>
<script src="https://unpkg.co/gsap@3/dist/gsap.min.js"></script>

<div class="space h-1000"></div>

<div class="space h-500">
  <div class="box"></div>
</div>

<div class="space h-1000"></div>

<button onclick="resizeBox()">resizeBox</button>

4

1 回答 1

2

这有点棘手,因为您正在调整与固定相同的元素的大小。ScrollTrigger 会自动缓存尺寸等,因此当刷新发生时,ScrollTrigger 会清除所有内联样式(恰好清除了您设置的新值),然后恢复到其缓存状态。这是否是一个错误,我们(GreenSock)尚未确定:)

至于现在如何解决这种情况,您可以在盒子周围创建一个空容器并将其固定:

<div class="pin-container">
  <div class="box"></div>
</div>
trigger: ".pin-container"

演示

于 2020-11-03T19:12:26.117 回答