2012-11-23 80 views
2

我有一個圓形的div,跟着你的鼠標使用Javascript,但我希望它停止時,它擊中了容器div的邊緣。我會怎麼做?這裏是JavaScript的即時通訊使用:我該如何使用jQuery跟隨帶有div的光標?

var mouseX = 0, mouseY = 0; 
$(document).mousemove(function(e){ 
mouseX = e.pageX; 
mouseY = e.pageY; 
}); 

// cache the selector 
var follower = $("#follower"); 
var xp = 0, yp = 0; 
var loop = setInterval(function(){ 
// change 12 to alter damping higher is slower 
xp += (mouseX - xp)/12; 
yp += (mouseY - yp)/12; 
follower.css({left:xp, top:yp}); 

}, 30); 

,這裏是一切我到目前爲止有:jsFiddle

請幫忙,謝謝!

回答

3

你需要建立移動元素的限制...

var mouseX = 0, mouseY = 0, limitX = 150-15, limitY = 150-15; 
$(window).mousemove(function(e){ 
    mouseX = Math.min(e.pageX, limitX); 
    mouseY = Math.min(e.pageY, limitY); 
}); 

哪裏150是你的容器的寬度/高度,15是你的光標的大小

http://jsfiddle.net/fhmkf/

相關問題