2016-08-23 53 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

不是要去工作,因为用户必须将他的鼠标动画(走右侧或左侧)。 –