问题
请记住,鼠标悬停每秒被触发 10-30 次。
因此,您的代码每秒添加 10-30 个新的 setTimeout 回调。
这很快就会导致崩溃。
一种解决方案
监听舞台上的鼠标移动。
将包含粉红色面板的图层偏移超过鼠标移动距离以创建视差效果。
这是代码和小提琴:http: //jsfiddle.net/m1erickson/9bqrC/
<!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>
body{padding:20px;}
#container1{
border:solid 1px #ccc;
margin-top: 10px;
width:200px;
height:200px;
overflow:hidden;
}
</style>
<script>
$(function(){
var stage = new Kinetic.Stage({
container: 'container1',
width: 400,
height: 200
});
var layer = new Kinetic.Layer();
stage.add(layer);
// listen for mousemoves on container1
// create a "parallax" movement of layer by
// moving the layer more than the mousemove
$(stage.getContent()).on('mousemove', function (event) {
var pos=stage.getMousePosition();
var mouseX=parseInt(pos.x);
var mouseY=parseInt(pos.y);
layer.setX(-mouseX/.5);
layer.draw();
});
// create 12 panels (0-11)
for(var i=0;i<12;i++){
addPanel(i*50,"blue"+i);
}
layer.draw();
function addPanel(x,id){
var rect = new Kinetic.Rect({
id:"blue"+id,
x: x,
y: 0,
width: 50,
height: 200,
fill: 'pink',
stroke: 'lightgray',
strokeWidth: 3
});
rect.number=i;
rect.on("click",function(){
$("#results").text("You clicked panel#"+rect.number);
});
layer.add(rect);
var text= new Kinetic.Text({
x:i*50+(i<10?20:10),
y:0,
fontSize:30,
text:i,
fill:"white"
});
layer.add(text);
}
}); // end $(function(){});
</script>
</head>
<body>
<h3>Drag the mouse to view panels in parallax</h3>
<h3>Click on a panel to trigger its own click event</h3>
<p id="results">Results</p>
<div id="container1"></div>
</body>
</html>