CSS js on mousemove 重绘不消失
CSS js on mousemove redraw without disappear
我用鼠标在 window 上用 CSS 画圆圈。然后我慢慢移动光标很好地重绘,但如果我更快地移动光标,我可以看到圆圈是如何消失的。怎样才能顺利重绘而不消失?
我在下面尝试的代码:
.circle {
position: absolute;
width:100px;
height:100px;
border-radius:50px;
border: 1px solid #000
}
<div class="circle"> </div>
$(window).mousemove(function(e) {
var x = e.clientX;
var y = e.clientY;
$(".circle").css("left", x-50); //-50 for center because circle width = 100
$(".circle").css("top", y-50); //-50 for center because circle height = 100
});
可能会解决您的问题的两个优化:
- 在 mousemove
之前在变量中缓存 $(".circle")
- 使用
transform: translate3d(x,y,z)
代替left+top
另一种方法是使用 animate,而不是 @zvona 所说的也很有魅力:
<script>
$(window).mousemove(function(e) {
var x = e.clientX;
x = x-50;
var y = e.clientY;
y = y-50;
$(".circle").animate({"left": x+"px", "top": y+"px"}, 0);
});
</script>
最后的0是到达光标的时间,以毫秒为单位。你可以让它更流畅,例如,10 毫秒。
顺便说一下,我在 Chrome 和 Firefox 上试过你的代码,在 MAC 上,我没有看到它消失得更快。
我用鼠标在 window 上用 CSS 画圆圈。然后我慢慢移动光标很好地重绘,但如果我更快地移动光标,我可以看到圆圈是如何消失的。怎样才能顺利重绘而不消失?
我在下面尝试的代码:
.circle {
position: absolute;
width:100px;
height:100px;
border-radius:50px;
border: 1px solid #000
}
<div class="circle"> </div>
$(window).mousemove(function(e) {
var x = e.clientX;
var y = e.clientY;
$(".circle").css("left", x-50); //-50 for center because circle width = 100
$(".circle").css("top", y-50); //-50 for center because circle height = 100
});
可能会解决您的问题的两个优化:
- 在 mousemove 之前在变量中缓存
- 使用
transform: translate3d(x,y,z)
代替left+top
$(".circle")
另一种方法是使用 animate,而不是 @zvona 所说的也很有魅力:
<script>
$(window).mousemove(function(e) {
var x = e.clientX;
x = x-50;
var y = e.clientY;
y = y-50;
$(".circle").animate({"left": x+"px", "top": y+"px"}, 0);
});
</script>
最后的0是到达光标的时间,以毫秒为单位。你可以让它更流畅,例如,10 毫秒。
顺便说一下,我在 Chrome 和 Firefox 上试过你的代码,在 MAC 上,我没有看到它消失得更快。