// 获取按钮和状态元素 const forwardBtn = document.getElementById('forwardBtn'); const backwardBtn = document.getElementById('backwardBtn'); const status = document.getElementById('status'); // 实际控制函数 function controlMotor(direction) { // 根据方向设置状态消息 if (direction === 'stop') { status.innerHTML = `

正在停止...

`; } else { status.innerHTML = `

正在${direction === 'forward' ? '前进' : '后退'}...

`; } // 记录操作(如果正在录制) if (window.isRecording) { const timestamp = Date.now() - window.recordingStartTime; window.recordedActions.push({ direction, timestamp }); console.log('Recorded action:', { direction, timestamp }); } else { console.log('Not recording, action:', direction); } // 发送AJAX请求到后端服务器 fetch('/control', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ direction: direction }) }) .then(response => response.json()) .then(data => { if (data.status === 'success') { status.innerHTML = `

${data.message}

`; } else { status.innerHTML = `

错误: ${data.message}

`; } }) .catch(error => { status.innerHTML = `

通信错误: ${error.message}

`; }); } // 按钮按下和松开事件 // 前进按钮 - 支持鼠标和触摸事件 forwardBtn.addEventListener('mousedown', () => { // 发送前进请求 controlMotor('forward'); }); forwardBtn.addEventListener('mouseup', () => { // 停止电机 stopMotor(); }); forwardBtn.addEventListener('mouseleave', () => { // 鼠标离开按钮时也停止 stopMotor(); }); // 前进按钮 - 触摸事件 forwardBtn.addEventListener('touchstart', (e) => { e.preventDefault(); // 防止默认行为 // 发送前进请求 controlMotor('forward'); }); forwardBtn.addEventListener('touchend', (e) => { e.preventDefault(); // 防止默认行为 // 停止电机 stopMotor(); }); forwardBtn.addEventListener('touchcancel', (e) => { e.preventDefault(); // 防止默认行为 // 触摸被取消时停止电机 stopMotor(); }); // 后退按钮 - 支持鼠标和触摸事件 backwardBtn.addEventListener('mousedown', () => { // 发送后退请求 controlMotor('backward'); }); backwardBtn.addEventListener('mouseup', () => { // 停止电机 stopMotor(); }); backwardBtn.addEventListener('mouseleave', () => { // 鼠标离开按钮时也停止 stopMotor(); }); // 后退按钮 - 触摸事件 backwardBtn.addEventListener('touchstart', (e) => { e.preventDefault(); // 防止默认行为 // 发送后退请求 controlMotor('backward'); }); backwardBtn.addEventListener('touchend', (e) => { e.preventDefault(); // 防止默认行为 // 停止电机 stopMotor(); }); backwardBtn.addEventListener('touchcancel', (e) => { e.preventDefault(); // 防止默认行为 // 触摸被取消时停止电机 stopMotor(); }); // 停止电机函数 function stopMotor() { // 记录操作(如果正在录制) if (window.isRecording) { const timestamp = Date.now() - window.recordingStartTime; window.recordedActions.push({ direction: 'stop', timestamp }); console.log('Recorded action:', { direction: 'stop', timestamp }); } // 发送停止请求到服务器 fetch('/control', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ direction: 'stop' }) }) .then(response => response.json()) .then(data => { if (data.status === 'success') { // 停止成功,不显示消息 } else { status.innerHTML = `

错误: ${data.message}

`; } }) .catch(error => { status.innerHTML = `

通信错误: ${error.message}

`; }); }