2016-08-23 77 views
1

我想將我溢出的div(在窗口加載時計算)向右或向左取決於用戶的鼠標位置。 (連續動畫,而鼠標仍然在那裏)。我有一些錯誤/問題。jQuery鼠標懸停,向左或向右動畫

  1. 鼠標仍然移動時不停地移動方向。
  2. 如果我使用動畫功能,這將與開始和停止一遍又一遍地導致壞動畫。

任何想法?

注:我不想使用除jQuery之外的任何額外的庫。

$(window).load(function() { 
    var buildingsWrapper = $('#buildings'), 
     lastBuilding = $('.building:last'); 

    buildingsWrapper.width(parseInt(lastBuilding.css('left')) + lastBuilding.width()); 

    var followMouseMove = function() { 
     var animStarted = false; 

     // ok now, mouse over but this will work for just one time. 
     buildingsWrapper.on('mouseover', function(e) { 
      if(e.clientX >= $(window).width() - 100) { 
       var left = buildingsWrapper.css('left'); 

       if(!animStarted) { 
        animStarted = true; 

        // will work but will stop and start again after animStarted set to false. that start/stop is not what i want. 
        buildingsWrapper.animate({ 
         left: parseInt(left) - 50 
        }, 300, function() { 
         animStarted = false; 
        }); 
       } 
      } 
     }); 
    }; 

    followMouseMove(); 
}); 

回答

0

嘗試鼠標移動:

buildingsWrapper.on('mouseover', function(){ 
    $(document).mousemove(function(e) { 
      var mouseX = e.pageX; 
      var slideT = (mouseX*(-1))+"px"; 



     buildingsWrapper.css({'left': slideT}); 
});  
     }); 

嘗試修改slideT讓動畫你想

+0

不是要去工作,因爲用戶必須將他的鼠標動畫(走右側或左側)。 –