如何使用鼠标或触摸更改数字输入字段

How can I change a numeric input field with the mouse or touch?

本文关键字:数字输入 字段 触摸 何使用 鼠标      更新时间:2023-12-25

我想创建一个输入字段,您可以在其中单击/触摸,然后向上或向下移动以更改字段的值,直到释放鼠标/手指。

这应该适用于最近的浏览器以及Android和iPhone。

这里有一个快速简单的方法来完成

<!doctype html>
<html>
  <head>
    <script type='text/javascript'>
      var startY;
      function loadJs(){
        document.getElementById("upDownInput").onmousedown = startMoveUpDown;
      }      
      function startMoveUpDown(e){
        startY = e.clientY;
        document.onmousemove = moveUpDown;
        document.onmouseup = endMoveUpDown;
      }
      function moveUpDown(e){
        var input = document.getElementById("upDownInput");
        var moveChange = Math.ceil(e.clientY - startY);        
        input.value = moveChange;
      }
      function endMoveUpDown(){
        document.onmousemove = null;
      }
    </script>
  </head>
  <body onload='loadJs()'>
    <input style='margin-top: 200px' value='0' type='number' id='upDownInput'/>
  </body>
</html>

您可能需要签出jQuery UI的滑块,以获得可靠的跨浏览器滑块。