【Copilotの答えの始め】
JavaScriptでスマホとPCの両方で範囲指定およびそのキャンセルができるコードは以下のようになります。このコードは、 touchstart, touchend, mousedown, mouseup イベントを使用して、タッチデバイスおよびマウスデバイスの両方で範囲指定を実装し、そのキャンセルも行います。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
let startX, startY, endX, endY, isSelecting = false; const onMouseDown = (event) => { startX = event.clientX; startY = event.clientY; isSelecting = true; }; const onMouseUp = (event) => { if (!isSelecting) return; endX = event.clientX; endY = event.clientY; isSelecting = false; selectRange(startX, startY, endX, endY); }; const onTouchStart = (event) => { const touch = event.touches[0]; startX = touch.clientX; startY = touch.clientY; isSelecting = true; }; const onTouchEnd = (event) => { if (!isSelecting) return; const touch = event.changedTouches[0]; endX = touch.clientX; endY = touch.clientY; isSelecting = false; selectRange(startX, startY, endX, endY); }; const onCancelSelection = () => { // 選択範囲をキャンセルする処理をここに記述 }; const selectRange = (x1, y1, x2, y2) => { // 選択範囲を適用する処理をここに記述 console.log(`Selected range: (${x1}, ${y1}) to (${x2}, ${y2})`); }; document.addEventListener('mousedown', onMouseDown); document.addEventListener('mouseup', onMouseUp); document.addEventListener('touchstart', onTouchStart); document.addEventListener('touchend', onTouchEnd); document.addEventListener('keydown', (event) => { if (event.key === 'Escape') { onCancelSelection(); } }); |
このコードでは、 mousedown と mouseup イベントがマウスの操作を処理し、 touchstart と touchend イベントがタッチ操作を処理しています。また、 Escape キーを押すことで選択範囲をキャンセルすることができます。
【Copilotの答えの終わり】
夏の水深く眠らむ翡翠の目
