2014-02-12 103 views
0

其實我是JavaScript的初學者,我需要JavaScript功能的一項要求。 每當我將鼠標放在我的標誌上時,該標誌應該移動到身體上。這意味着當我將鼠標光標放在徽標上時,應該離開該位置並移動到其他位置。Javascript logo移動鼠標懸停功能

我在嘗試,但代碼不適合我。任何人都可以在這方面提出建議。作爲參考,我粘貼下面的鏈接爲gif圖像。

<script type="javascript"> 
    $("#logo").mouseover(function(){ 
     if(!logoMove){return;} 
     var tmp=new Array(
      {left:10,        top:10}, 
      {left:10,        top:$("#bodycontainer").height()-220}, 
      {left:$("#bodycontainer").width()-220, top:$("#bodycontainer").height()-220}, 
      {left:$("#bodycontainer").width()/2, top:$("#bodycontainer").height()/2}, 
      {left:$("#bodycontainer").width()-220, top:20} 
     ); 
     var rand = Math.floor(Math.random() * tmp.length); 
     while(tmp[rand].left == $(this).css("left") && 
      tmp[rand].top == $(this).css("top")){ 
      rand = Math.floor(Math.random() * tmp.length); 
     } 
     $(this).stop().animate({ 
       left:tmp[rand].left, 
       top:tmp[rand].top 
      }, 
      400 
     ); 
    }); 
} 
<script> 

<div id="logo"> 
    <img width="500" height="462" src="http://www.gameark.com/templates/onarcade/images/logo.png" > 
</div> 

僅供參考點擊link.

+0

看看這一個http://stackoverflow.com/questions/7031701/moving-an-image-10px-on-hover-and-changing-opacity – Pavlo

+0

這裏是我發現的一篇文章。嘗試這個。 http://stackoverflow.com/questions/11929687/tricky-button-moving-away-when-mouseover-in-javascriptl – CodeMonkey

回答

0

試試這個:

var logoMoved = false; 
var _k = 0; 
$("#logo").on("mouseenter",function(){ 
    if(logoMoved) return; 
    var tmp = [ 
     { 
      left:10, 
      top:10 
     }, 
     { 
      left:10, 
      top:$("#bodycontainer").height()-220 
     }, 
     { 
      left:$("#bodycontainer").width()-220, 
      top:$("#bodycontainer").height()-220 
     }, 
     { 
      left:$("#bodycontainer").width()/2, 
      top:$("#bodycontainer").height()/2 
     }, 
     { 
      left:$("#bodycontainer").width()-220, 
      top:20 
     } 
    ]; 
    logoMoved = true; 
    var _n = Math.floor(Math.random() * tmp.length);; 
    while(_k == _n){ 
     _n = Math.floor(Math.random() * tmp.length); 
    } 
    _k = _n; 
    $(this).animate({ 
     left:tmp[_k].left, 
     top:tmp[_k].top 
    },400,function(){ 
     logoMoved = false; 
    }); 
}); 

您可以使用以下兩種方法之一:在$

  1. 停止()(本).animate到停止當前的動畫,並做另一個(我不喜歡這種方式)
  2. logo移動變量以防止anuimation結束前的鼠標懸停。

在你的例子中,你同時使用......它似乎沒用。

例如:http://jsfiddle.net/8g3wy/1/ 我希望它可以幫助。

+0

謝謝Frogmouth。這是我所期望的。 –

+0

yeee ...我很樂意提供幫助。 – Frogmouth