如果鼠標位於屏幕左側,並且如果鼠標位於屏幕右側,使用javascript,則此圖像是我迄今爲止的代碼:如何使用JS根據鼠標位置移動圖像?
var dirx = 0;
var spdx = 35;
var imgLeftInt;
var imgTopInt;
var imgHeight;
var imgWidth;
var divWidth;
var divHeight;
var t;
var tempX;
var tempY;
所以我敢肯定我絕不錯過任何變量...
function animBall(on) {
imgLeftInt = parseInt(document.images['logo'].style.left);
imgTopInt = parseInt(document.images['logo'].style.top);
imgHeight = parseInt(document.images['logo'].height);
imgWidth = parseInt(document.images['logo'].width);
divWidth = parseInt(document.images['container'].width);
if (tempX > 779){
dirx = 1;
}
else if(tempX < 767){
dirx = 2;
}
else {
spdx = 0;
}
所以,如果tempX,這應該是X鼠標位置座標,比779大,這是div標籤的中間點,圖片應該是正確的。如果它低於這個數字,它應該離開,否則,速度應該是零,因爲它應該保持不變。
if(dirx == 1){
goRight();
} else if(dirx == 2) {
goLeft();
}
}
function getMouseXY(e) {
tempX = e.clientX;
tempY = e.clientY;
}
我發現了數百種不同的方式來獲取鼠標位置,但這是關閉的W3C,所以我認爲它的工作原理。
function goRight() {
document.images['logo'].style.left = imgLeftInt+spdx +"px";
if (imgLeftInt > (divWidth-imgWidth)){
dirx = 2;
spdx= 20;
}
}
function goLeft() {
document.images['logo'].style.left = (imgLeftInt-spdx) +"px";
if (imgLeftInt < 5){
dirx = 1;
spdx= 20;
}
}
</script>
這就是我的整個腳本。
<div id="container" onmousemove="getMouseXY(event);" width="1546" height="423">
<a href="javascript:var t=setInterval('animBall()', 80)">Start Animation</a> <a href="javascript:clearInterval(t);">Stop Animation</a> <br />
<img src="http://qabila.tv/images/logo_old.png" style="position:absolute;left:10px;top:20px;" id="logo" />
</div>
我留在了鼠標的位置到最後的依賴關係,動畫腳本能正常工作(或者至少工作,除非我打破了東西好一會纔讀鼠標位置)。
任何想法我做錯了什麼?
如果它的任何幫助,我已經主持了代碼here.
我託管的代碼[這裏](http://qabila.tv/teamlab/test4.html),不知道我做錯了什麼,但似乎沒有任何變化。 – JustSomeDude 2013-04-30 12:57:57