Detect if input was touched (tablet) or clicked (mouse)

淺唱寂寞╮ 提交于 2020-07-20 07:12:07

问题


We are developing a Web-App, which launches on Desktop and on tablets (iPad, Android or a surface). Now we are building our own keyboard for number inputs. When you set the focus on an input field with a mousclick, the costum keyboard opens correct. But when you set the focus to the input with a touched click (tablet), the default keyboard opens also. Our idea is, to detect, if there was a mouse-click or a touched click. If it's a touched click, we can set the readonly="true" property to the input, so the default keyboard on a tabled wouldn't slide in.

Is there a way to detect or check which "type" of click it was (touched or mouse).


回答1:


You can define an event for the both actions touchend and click then detect which one is triggered using type of the event :

$('#element-id').on('click touchend',function(e){
  if(e.type=='click')
      console.log('Mouse Click');
  else
      console.log('Touch');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="element-id">Click here</button>

Hope this helps.




回答2:


@Zakaria Acharki

        <script type="text/javascript">
        $(document).ready(function(){
            $(".cCostumeKeyboard").on("click touchstart",function(e){
                if(e.type=="click") {
                    alert("Mouse");
                    alert(e.type);
                }
                else if(e.type=="touchend"){
                    alert("Touch");
                    alert(e.type);
                    e.preventDefault();
                    e.stopPropagation();
                }
            }); 
        });
    </script>

Try this snippet on a touch device. It shows after the first touch on an input follow:

  • Alert: "Touches"
  • Alert: "touchend"
  • Alert: "Mouse"
  • Alert: "click"


来源:https://stackoverflow.com/questions/37110501/detect-if-input-was-touched-tablet-or-clicked-mouse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!