我正在为我的网站开发一个视差解决方案,每次用户移动光标时都会获得鼠标位置。我遇到的问题是当我点击文档的任何地方时,浏览器变得迟钝而且紧张。我能够记录光标的位置而没有任何延迟,但是文档本身的移动显示是不稳定的。
这就是我获得鼠标位置的方式
this.onMove=function(posX, posY){
bigX = $('#Stage').width();
bigY = $('#Stage').height();
console.log(posX+" - "+posY); //this is working properly in real-time
posX = bigX/2 - (posX);
posY = bigY/2 - (posY);
for(i = 1; i<4; i++){ //the part that seems to be lagging
$('.layer'+(i-1)+'').css({"-webkit-transform":"translate("+posX/50*i+"px,"+posY/50*i+"px)"});
}
}
$(document).mousemove(function(e){
this.onMove(e.pageX, e.pageY);
});
我也尝试在没有for循环的情况下实现翻译,但结果是一样的。这是浏览器陷入困境的问题,还是某种onclick事件可能会陷入循环?
答案 0 :(得分:1)
我做了一个测试CopePen以了解问题...
由于没有提供代码。
在玩它的时候(我真的很开心!),我发现了一些应该考虑的事情。
translate()
。前两者更多是关于性能问题......
但你的主要问题是关于鼠标点击&#34;干扰&#34; ...如果我做得不好
我在这个非常简单的代码中注意到了它!
人们不能说有很多元素在移动......
但是,当你按住鼠标并移动时会发生这种情况,就像拖动一样 并非总是在第一......但它确实发生了。
我使用preventDefault()
和return false
修复了#Stage
div内的这些鼠标事件:
mousedown
mouseup
click
所以在this codePen中,您可以使用按钮来查看所有这些效果。
我希望你会喜欢这方面的努力。 ;)
以下是我建议的onMove
功能:
(我删除了CodePen中的内容)
function onMove(posX, posY){
bigX = $('#Stage').width();
bigY = $('#Stage').height();
console.log(posX+" - "+posY); //this is working properly in real-time
// Make most of your calculation ONCE
posX = (bigX/2 - (posX))/50;
posY = (bigY/2 - (posY))/50;
// Translating layers now
for(i = 1; i<4; i++){
// Make the multiplication ONCE
var thisLayerPosX = posX*i;
var thisLayerPosY = posY*i;
// Limit decimals
thisLayerPosX = thisLayerPosX.toFixed(3);
thisLayerPosY = thisLayerPosY.toFixed(3);
var k = i-1;
$('.layer'+k).css({"-webkit-transform":"translate("+thisLayerPosX+"px,"+thisLayerPosY+"px)"});
}
}
我认为3位小数是可以的 它保持层运动平稳 1或0使它&#34;像素跳跃&#34;。