代码之家  ›  专栏  ›  技术社区  ›  TM. Randy Simon

JavaScript:检查鼠标按钮是否按下?

  •  115
  • TM. Randy Simon  · 技术社区  · 16 年前

    有没有一种方法可以检测JavaScript中的鼠标按钮当前是否已按下?

    15 回复  |  直到 16 年前
        1
  •  161
  •   rightfold Eugene Lazutkin    11 年前

    关于Pax的解决方案:如果用户有意或无意地单击多个按钮,则该解决方案不起作用。不要问我是怎么知道的。

    正确的代码应如下所示:

    var mouseDown = 0;
    document.body.onmousedown = function() { 
      ++mouseDown;
    }
    document.body.onmouseup = function() {
      --mouseDown;
    }
    

    通过这样的测试:

    if(mouseDown){
      // crikey! isn't she a beauty?
    }
    

    如果您想知道按下了什么按钮,请准备将鼠标向下移动一组计数器,并分别计算各个按钮的数量:

    // let's pretend that a mouse doesn't have more than 9 buttons
    var mouseDown = [0, 0, 0, 0, 0, 0, 0, 0, 0],
        mouseDownCount = 0;
    document.body.onmousedown = function(evt) { 
      ++mouseDown[evt.button];
      ++mouseDownCount;
    }
    document.body.onmouseup = function(evt) {
      --mouseDown[evt.button];
      --mouseDownCount;
    }
    

    if(mouseDownCount){
      // alright, let's lift the little bugger up!
      for(var i = 0; i < mouseDown.length; ++i){
        if(mouseDown[i]){
          // we found it right there!
        }
      }
    }
    

    • 1左
    • 2为右

    记住:IE使用一个名为“事件”的全局事件对象。

    顺便说一句,IE有一个在您的情况下很有用的特性:当其他浏览器只为鼠标按钮事件(onclick、onmousedown和onmouseup)发送“button”时,IE也会随onmousemove一起发送。因此,您可以在需要了解按钮状态时开始监听onmousemove,并在获得evt.button后立即检查它-现在您知道按下了哪些鼠标按钮:

    // for IE only!
    document.body.onmousemove = function(){
      if(event.button){
        // aha! we caught a feisty little sheila!
      }
    };
    

    相关链接:

    更新#1 :我不知道为什么我要继续使用document.body-style代码。最好将事件处理程序直接附加到文档。

        2
  •  51
  •   Jono Job    7 年前

    mousedown mouseup 跟踪按钮是否被按下。但正如其他人指出的那样, 松开鼠标

    MouseEvent (现在)指示当前按下的按钮:

    document mousemove 将在光标重新进入浏览器时立即触发,因此如果用户在外部释放,则状态将在鼠标返回内部时立即更新。

    var leftMouseButtonOnlyDown = false;
    
    function setLeftButtonState(e) {
      leftMouseButtonOnlyDown = e.buttons === undefined 
        ? e.which === 1 
        : e.buttons === 1;
    }
    
    document.body.onmousedown = setLeftButtonState;
    document.body.onmousemove = setLeftButtonState;
    document.body.onmouseup = setLeftButtonState;
    

        3
  •  19
  •   paxdiablo    16 年前

    我认为最好的方法是保存您自己的鼠标按钮状态记录,如下所示:

    var mouseDown = 0;
    document.body.onmousedown = function() { 
        mouseDown = 1;
    }
    document.body.onmouseup = function() {
        mouseDown = 0;
    }
    

    然后,在代码的后面:

    if (mouseDown == 1) {
        // the mouse is down, do what you have to do.
    }
    
        4
  •  14
  •   alfred    14 年前

    唯一好的解决方案是使用IE.event对象。

        5
  •  8
  •   Martin    8 年前

    我知道这是一篇老文章,但我觉得用鼠标上下移动鼠标按钮有点笨重,所以我找到了一个可能吸引一些人的替代方法。

    <style>
        div.myDiv:active {
            cursor: default;
        }
    </style>
    
    <script>
        function handleMove( div ) {
            var style = getComputedStyle( div );
            if (style.getPropertyValue('cursor') == 'default')
            {
                // You're down and moving here!
            }
        }
    </script>
    
    <div class='myDiv' onmousemove='handleMove(this);'>Click and drag me!</div>
    

    :active选择器比mouse up/down更好地处理鼠标点击,您只需要在onmousemove事件中读取该状态。为此,我需要作弊,并依赖于默认光标是“auto”,而我只是将其更改为“default”,这是auto默认选择的。

    我本想在:active部分设置自己的用户定义样式,但我无法实现。如果可能的话会更好。

        6
  •  4
  •   Jake Devine Jake Devine    16 年前

    我建议对跨浏览器事件附件使用一些方法—显式设置mousedown和mouseup属性是为了简化示例。

    function doStuff() {
      // does something when mouse is down in body for longer than 2 seconds
    }
    
    var mousedownTimeout;
    
    document.body.onmousedown = function() { 
      mousedownTimeout = window.setTimeout(doStuff, 2000);
    }
    
    document.body.onmouseup = function() {
      window.clearTimeout(mousedownTimeout);
    }
    
        7
  •  3
  •   Micah Engle-Eshleman    7 年前

    如果您使用现有的鼠标事件处理程序在一个复杂的页面中工作,我建议您在 (而不是泡沫)。为此,只需设置 addEventListener true .

    此外,您可能需要检查 event.which elem.dispatchEvent(new Event('mousedown')) .

    var isMouseDown = false;
    
    document.addEventListener('mousedown', function(event) { 
        if ( event.which ) isMouseDown = true;
    }, true);
    
    document.addEventListener('mouseup', function(event) { 
        if ( event.which ) isMouseDown = false;
    }, true);
    

    窗外 仍有记录。

        8
  •  2
  •   Jake Devine Jake Devine    16 年前

    您可以将@Pax和my answers组合在一起,以获得鼠标已按下的持续时间:

    var mousedownTimeout,
        mousedown = 0;
    
    document.body.onmousedown = function() {
      mousedown = 0; 
      window.clearInterval(mousedownTimeout);
      mousedownTimeout = window.setInterval(function() { mousedown += 200 }, 200);
    }
    
    document.body.onmouseup = function() {
      mousedown = 0;
      window.clearInterval(mousedownTimeout);
    }
    

    随后:

    if (mousedown >= 2000) {
      // do something if the mousebutton has been down for at least 2 seconds
    }
    
        9
  •  2
  •   Thomas Hansen    16 年前

        10
  •  2
  •   Zachary Kniebel    12 年前

    短而甜

    我不知道为什么之前的答案对我都不起作用,但我在一瞬间想出了这个解决方案。它不仅有效,而且非常优雅:

    添加到正文标记:

    onmouseup="down=0;" onmousedown="down=1;"
    

    myfunction() 如果 down 1 :

    onmousemove="if (down==1) myfunction();"
    
        11
  •  2
  •   David    11 年前

    使用jQuery,下面的解决方案甚至可以处理“拖出页面然后发布案例”。

    $(document).mousedown(function(e) {
        mouseDown = true;
    }).mouseup(function(e) {
        mouseDown = false;
    }).mouseleave(function(e) {
        mouseDown = false;
    });
    

    我不知道它如何处理多个鼠标按钮。

        12
  •  2
  •   illogicalapple    4 年前

    如果其他人遇到这种情况,您可以使用 .matches :active 选择器:

    function mouseDown() {
        return document.body.matches(":active");
    }
    
        13
  •  1
  •   NVRM    6 年前

    使用 MouseEvent

    document.addEventListener('mousedown', (e) => console.log(e.buttons))

    Return :

    表示一个或多个按钮的数字。用于多个按钮 同时按下,组合值(例如,3为主要值+ 二级)。

    0 : No button or un-initialized
    1 : Primary button (usually the left button)
    2 : Secondary button (usually the right button)
    4 : Auxilary button (usually the mouse wheel button or middle button)
    8 : 4th button (typically the "Browser Back" button)
    16 : 5th button (typically the "Browser Forward" button)
    
        14
  •  0
  •   Marcin Å»urek    10 年前

    在jQuery示例下面,当鼠标位于$('.element')上方时,颜色会根据按下的鼠标按钮而变化。

    var clicableArea = {
        init: function () {
            var self = this;
            ('.element').mouseover(function (e) {
                self.handlemouseClick(e, $(this));
            }).mousedown(function (e) {
                self.handlemouseClick(e, $(this));
            });
        },
        handlemouseClick: function (e, element) {
            if (e.buttons === 1) {//left button
                element.css('background', '#f00');
            }
            if (e.buttons === 2) { //right buttom
                element.css('background', 'none');
            }
        }
    };
    $(document).ready(function () {
        clicableArea.init();
    });
    
        15
  •  0
  •   dreadcast    7 年前

    mouseup 发生在浏览器窗口之外,我们不知道。。。

    window.addEventListener('mouseup', mouseUpHandler, false);
    window.addEventListener('mousedown', mouseDownHandler, false);
    

    松开鼠标

    • 用户同时按下键盘键和鼠标键,在浏览器窗口外释放鼠标键,然后释放键。
    • 用户按 鼠标按钮同时释放一个鼠标按钮,然后释放另一个鼠标按钮,两者都在浏览器窗口之外。
        16
  •  -1
  •   user2550945    12 年前
            var mousedown = 0;
            $(function(){
                document.onmousedown = function(e){
                    mousedown = mousedown | getWindowStyleButton(e);
                    e = e || window.event;
                    console.log("Button: " + e.button + " Which: " + e.which + " MouseDown: " + mousedown);
                }
    
                document.onmouseup = function(e){
                    mousedown = mousedown ^ getWindowStyleButton(e);
                    e = e || window.event;
                    console.log("Button: " + e.button + " Which: " + e.which + " MouseDown: " + mousedown);
                }
    
                document.oncontextmenu = function(e){
                    // to suppress oncontextmenu because it blocks
                    // a mouseup when two buttons are pressed and 
                    // the right-mouse button is released before
                    // the other button.
                    return false;
                }
            });
    
            function getWindowStyleButton(e){
                var button = 0;
                    if (e) {
                        if (e.button === 0) button = 1;
                        else if (e.button === 1) button = 4;
                        else if (e.button === 2) button = 2;  
                    }else if (window.event){
                        button = window.event.button;
                    }
                return button;
            }
    

        17
  •  -3
  •   rogeriopvl    16 年前

    嗯,你不能在活动结束后检查它是否下降,但你可以检查它是否上升。。。如果有空。。这意味着不再是下降:P lol

    因此,用户按下按钮(onMouseDown事件)。。。然后,您检查是否已启动(onMouseUp)。虽然还没有结束,你可以做你需要的。

    推荐文章