我正在使用 Kinetic.js 在画布中进行一些拖动,并且试图检测鼠标是否离开浏览器窗口。唯一的区别是我还希望它在移出时按下鼠标按钮时触发。
这个线程几乎解决了这个问题,但是如果你在移出时按下鼠标左键它不起作用:链接
对我来说,只要按下鼠标左键,mouseout 事件似乎就会被忽略。我在这里做了一个测试。有任何想法吗?
您可以在按下鼠标时设置 isDown 标志。然后在释放鼠标时清除 isDown 标志。并跟踪 mouseout + isDown 标志以查看用户是否在按下鼠标时离开
这是 jQuery 版本:
var isDown=false;
$(stage.getContent()).on('mousedown',function(e){ isDown=true; });
$(stage.getContent()).on('mouseup',function(e){ isDown=false; });
$(stage.getContent()).on('mouseout',function(e){
console.log(isDown);
isDown=false;
});
这是代码和小提琴:http: //jsfiddle.net/m1erickson/ZjKGS/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Prototype</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.7.0.min.js"></script>
<style>
#container{
border:solid 1px #ccc;
margin-top: 10px;
width:400px;
height:400px;
}
</style>
<script>
$(function(){
var stage = new Kinetic.Stage({
container: 'container',
width: 300,
height: 300
});
var layer = new Kinetic.Layer();
stage.add(layer);
var isDown = false;
$(stage.getContent()).on('mousedown', function (e) {
isDown = true;
});
$(stage.getContent()).on('mouseup', function (e) {
isDown = true;
});
$(stage.getContent()).on('mouseout', function (e) {
if(isDown){
$("#indicator").text("Moved out and mouse was pressed");
}else{
$("#indicator").text("Moved out and mouse was not pressed");
}
isDown = false;
});
layer.draw();
}); // end $(function(){});
</script>
</head>
<body>
<p>Move mouse out of kinetic stage</p>
<p>Indicator will tell if mouse was also pressed</p>
<p id="indicator">Indicator</p>
<div id="container"></div>
</body>
</html>