2017-04-11 29 views
1

我正在元素上創建一個「mousedown」事件,並且如果按下shift鍵則切換變量。我還想在發生「mouseup」事件時將變量設置爲false。如何添加mouseup事件jquery

element.addEventListener("mousedown", (e)=>{ 
      if(e.shiftKey){ 
       this.start = true; 
      } else { 
       this.start = false; 
      } 
     }); 

我想使this.start爲假時mouseup上面的代碼後,隨後發生。任何人都可以幫我解決這個問題。

謝謝。

回答

1

首先偵聽按下Shift鍵

var shiftIsPressedDown = false; 
$(window).keydown(function(evt) { 
    if (evt.which == 16) { // shift 
    shiftIsPressedDown = true; 
    } 
}).keyup(function(evt) { 
    if (evt.which == 16) { // shift 
    shiftIsPressedDown = false; 
    } 
}); 

然後看看鼠標按下事件

$("#target").mousedown(function() { 
    if(shiftIsPressedDown){ 
    // Do logic here  
    } 
}); 
+0

你是救世主:)感謝一噸:) – zelda

1

採取在https://api.jquery.com/mouseup/它談論這是你在找什麼,因爲我相信

.mouseup() 

功能看看。它基本上是簡寫以下語法:

可用於像這樣:

$("#target").mouseup(function() { 
    alert("Handler for .mouseup() called."); 
}); 

從文檔的完整的例子如下:

<!doctype html> 
<html lang="en"> 
<head> 
    <meta charset="utf-8"> 
    <title>mouseup demo</title> 
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script> 
</head> 
<body> 

<p>Press mouse and release here.</p> 

<script> 
$("p") 
    .mouseup(function() { 
    $(this).append("<span style='color:#f00;'>Mouse up.</span>"); 
    }) 
    .mousedown(function() { 
    $(this).append("<span style='color:#00f;'>Mouse down.</span>"); 
    }); 
</script> 

</body> 
</html> 
-1

我相信這是工作的代碼這個問題,改編自:jQuery keyboard event handler press and hold

var keysdown = {}; 
// keydown handler 
$(document).keydown(function(e){ 
    // Do we already know it's down? 
    if (keysdown[e.keyCode]) { 
     // Ignore it 
     return; 
    } 
    // Remember it's down 
    keysdown[e.keyCode] = true; 

    // Do our thing 
    if (e.keyCode == 16){ 
     $(document).mousedown(function(){ 
     //this.start = true;     
     console.log("this.start=true") 
     }); 
     $(document).mouseup(function(){ 
     //this.start = false; 
     console.log("this.start=false") 
     }); 
    } 
}); 
// keyup handler 
$(document).keyup(function(e){ 
    // Remove this key from the map 
    delete keysdown[e.keyCode]; 
});