You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让GSAP仅在按住鼠标按钮时应用缩放效果?

解决GSAP横向滑块仅按住鼠标时缩放的问题

问题说明

我使用GSAP实现了一个横向滑块,拖动时滑块的section会缩放。当前存在的问题是,点击时就会触发缩放,且缩放状态会持续到拖动结束后。需要实现仅在按住鼠标按钮时才应用缩放效果。

解决方案

核心是区分点击与拖动行为,并覆盖所有鼠标释放场景来恢复状态:

  • 替换onPress为onDragStart,仅在真正开始拖动时触发缩放
  • 添加onRelease事件,确保所有鼠标释放操作(包括点击未拖动)都能恢复缩放

修改后的完整代码

JavaScript

var drag = Draggable.create(".horizontalContainer ", {
  type: "x",
  onDragStart() {
    const scale = .6;
    gsap.to('.section', {scale: scale, duration: .25});
  },
  onRelease() {
    gsap.to('.section', {scale: 1, duration: .25});
  },
  onDragEnd() {
    const xpos = this.target.getBoundingClientRect().left;
    const winWidth = window.innerWidth;
    gsap.to(this.target, {x: Math.round(xpos / winWidth) * winWidth, duration: .5});
  }
});

CSS

body {
  margin: 0;
  padding: 0;
  overflow: hidden;
}

.horizontalContainer {
  width: 600%;
  display: flex;
  flex-wrap: nowrap;
}

.section {
  height: 100vh;
  width: 100vw;
  text-align: center;
  font-size: 36px;
  line-height: 90vh;
}

.section:nth-child(1) {
  background-color: #deb887;
}

.section:nth-child(2) {
  background-color: limegreen;
}

.section:nth-child(3) {
  background-color: #b8860b;
}

.section:nth-child(4) {
  background-color: #2f4f4f;
}

.proxy {
  position: absolute;
  visibility: hidden;
}

HTML

<script src="https://unpkg.com/gsap@3/dist/Draggable.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='horizontalContainer'>
    <div class='section'>ScrollTrigger with Draggable</div>
    <div class='section'></div>
    <div class='section'></div>
    <div class='section'></div>
</div>

逻辑解释

  1. onDragStart事件:只有当用户按下鼠标并开始拖动元素时才会触发,避免了单纯点击就触发缩放的问题
  2. onRelease事件:覆盖所有鼠标释放的场景——无论是拖动结束还是点击后直接释放,都会立即恢复section的缩放状态
  3. onDragEnd保留原定位逻辑:仅处理滑块的对齐定位,不影响缩放状态的重置逻辑

内容的提问来源于stack exchange,提问作者gjjr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 05:57:30