2012-08-31 65 views
4

我想在鼠標的狀態下狀態了狀態如何檢查當前的鼠標按鈕狀態使用JavaScript

document.onmousemove = mouseMove; 
document.onmousedown = mouseDown; 
document.onmouseup = mouseUp; 

function mouseMove(ev) { 

    mouseState=""; 
    //How can I know the state button of mouse button from here 
    if(mouseState=='down') { 
     console.log('mouse down state') 
    } 

    if(mouseState=='up') { 
     console.log('mouse up state') 
    } 
} 

function mouseDown(ev) { 
    console.log('Down State you can now start dragging'); 
    //do not write any code here in this function 
} 

function mouseUp(ev) { 
    console.log('up state you cannot drag now because you are not holding your mouse') 
    //do not write any code here in this function 
} 

,當我提出我的鼠標,程序應該顯示的要求值mouseState現在在控制檯上向下或向下移動

+0

此問題與[chrome問題](http://www.pmarks.net/posted_links/chromium_up_down_bug.html)有關。而IE也顯示出同樣的問題。有沒有解決方案 – vusan

+0

我想知道鼠標按鈕的狀態,因爲[this](http://stackoverflow.com/questions/12191743/how-to-know-the-current-state-of-mouse-buttonmouseup-狀態或mousedown狀態)問題。 – vusan

回答

2

您只需爲其創建一個變量。

document.onmousemove = mouseMove; 
document.onmousedown = mouseDown; 
document.onmouseup = mouseUp; 
var mouseState = "up"; 

function mouseMove(ev) { 

    //How can I know the state of mouse from here 
    if(mouseState=='down') { 
     console.log('mouse down state') 
    } 

    if (mouseState=='up') { 
     console.log('mouse up state') 
    } 
} 

function mouseDown(ev) { 
    mouseState = "down"; 
    console.log('Down State you can now start dragging'); 
    //do not write any code here in this function 
} 

function mouseUp(ev) { 
    mouseState = "up"; 
    console.log('up state you cannot drag now because you are not holding your mouse') 
    //do not write any code here in this function 
} 

您應該看看「mousemove」上的事件,方法是將其記錄到控制檯中。那裏可能有一個屬性表明鼠標的狀態,就像按鍵事件有一個屬性,告訴你是否按下了shift鍵。但是這可能不是跨瀏覽器兼容的。

3

您可以查看MouseEvent.which屬性。

function mouseMove(ev) { 
    if(ev.which==1) { 
     console.log('mouse down state with left click'); 
    } else if(ev.which==3) { 
     console.log('mouse down state with right click'); 
    } else { 
     console.log('mouse update'); 
    } 
} 
+0

非常感謝你真的爲我工作。 – vusan

+1

對不起,但現在我不使用這個解決方案,因爲它不會解決IE。還有其他的想法嗎? – vusan

+2

Bzzt。 Mousevent.which屬性告訴哪個按鈕導致了最近的'mousedown'或'mouseup'事件。它只是複製到'mousemove'事件中。它並不反映鼠標按鈕的當前狀態。它的名字似乎表明它確實如此 - 我熱切地希望它做到了 - 但事實並非如此。 (這不僅僅是一個IE或瀏覽器版本問題:-) –