2017-04-11 32 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]; 
});