简体   繁体   English

拖动时防止单击

[英]Prevent click when dragging

Im using Three.js to display a 3d model which users can drag the camera around and click objects to zoom in on them.我使用 Three.js 显示一个 3d 模型,用户可以拖动相机并单击对象以放大它们。 The issue I'm having is that when you click and drag it reads it as a click and triggers the animation, I need to prevent clicking when dragging, so clicks are only registered when it is just a click and no mouse movement.我遇到的问题是,当您单击并拖动它时,它会将其读取为单击并触发动画,我需要在拖动时防止单击,因此只有在单击且没有鼠标移动时才会注册单击。

 function onClick(event) { event.preventDefault(); mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1; mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1; raycaster.setFromCamera( mouse, camera ); var intersects = raycaster.intersectObjects( scene.children, true ); if ( intersects.length > 0 && intersects[0].object.name==="Tree006") { var object = intersects[0].object; gsap.to( camera.position, { duration: 1, x: mesh["Tree006"].position.x, y: mesh["Tree006"].position.y, z: mesh["Tree006"].position.z, onUpdate: function() { controls.enabled = false; camera.lookAt(0,0,0); } } ); console.log( 'Intersection:', intersects[ 0 ] ); } if ( intersects.length > 0 && intersects[0].object.name!=="Tree006") { var object = intersects[0].object; gsap.to( camera.position, { duration: 1, // seconds x: 6, y: 4, z: 6, onUpdate: function() { controls.enabled = true; camera.lookAt( 0,0,0 ); } } ); } }

Event click is only fired when you release the mouse button over the element.仅当您在元素上释放鼠标按钮时才会触发事件click So you can set some flag on mousedown and reset that flag on mouseup .因此,您可以在mousedown上设置一些标志并在mouseup上重置该标志。 This flag would tell the click handler not to do anything.这个标志会告诉click处理程序不要做任何事情。

 var btn1 = document.querySelector("#btn1"); var flag = false; btn1.addEventListener('click', function(ev) { if (!flag) { alert(1); } ev.preventDefault(); }) btn1.addEventListener('mousedown', function(ev) { flag = true; console.log("flag to disable click is true"); }) btn1.addEventListener('mouseup', function(ev) { // this is dirty hack, until i find a better solution: setTimeout(function() { flag = false console.log("flag to disable click is false"); }); })
 <button id="btn1">no click</button> <button id="btn2" onclick="alert(2)">click</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM