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

如何制作按下时持续执行函数、松开即停止的HTML按钮以实现相机移动

实现按住按钮持续移动物体的解决方案

核心实现逻辑

通过监听按钮的三类鼠标事件控制执行状态:

  • mousedown:鼠标按下时启动定时器,按固定间隔重复执行移动函数
  • mouseup:鼠标松开时清除定时器,停止移动
  • mouseleave:鼠标移出按钮区域时同步清除定时器,避免按钮外松开无法停止的异常

完整修改代码

JavaScript逻辑

var increment = 1; 
var moveTimer = null; // 全局存储移动定时器

function moveUp() {
  camera.position.z += increment;
}
function moveDown() {
  camera.position.z -= increment;
}
function moveRight() {
  camera.position.x += increment;
}
function moveLeft() {
  camera.position.x -= increment;
}

// 启动移动:传入对应方向的移动方法
function startMove(moveFunc) {
  // 先清空已有定时器,避免多个定时器叠加导致速度异常
  stopMove();
  // 立即执行一次,消除按下后的延迟感
  moveFunc();
  // 启动定时器,间隔50ms可按需调整,数值越小移动速度越快
  moveTimer = setInterval(moveFunc, 50);
}

// 停止移动
function stopMove() {
  if (moveTimer) {
    clearInterval(moveTimer);
    moveTimer = null;
  }
}

HTML按钮绑定示例

<button onmousedown="startMove(moveUp)" onmouseup="stopMove()" onmouseleave="stopMove()">向上移动</button>
<button onmousedown="startMove(moveDown)" onmouseup="stopMove()" onmouseleave="stopMove()">向下移动</button>
<button onmousedown="startMove(moveLeft)" onmouseup="stopMove()" onmouseleave="stopMove()">向左移动</button>
<button onmousedown="startMove(moveRight)" onmouseup="stopMove()" onmouseleave="stopMove()">向右移动</button>

可选适配项

如果需要支持移动端触摸操作,可给按钮额外绑定touchstart、touchend、touchcancel事件,逻辑和鼠标事件完全一致即可。

内容的提问来源于stack exchange,提问作者It's Joker

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 22:15:03