2012-10-21 37 views
0

我想讓它的滾動鼠標懸停在圖像上,但只能滾動到目前爲止。某處它只是不太工作JavaScript滾動對象由mouseover

$(document).ready(function() 
{ 
    $('#test').bind('mouseenter', function() 
    { 
    var self = $(this); 
    var right = parseInt(self.style.left) || 200;    
    this.iid = setInterval(function() 
    { 
     if (right <= 400) 
     {      
     right += 200;       
     } 
     else 
     { 
      right = 400;       
     } 
    self.style.left = right + "px"; 
    }, 525); 
    }).bind('mouseleave', function() 
      { 
    this.iid && clearInterval(this.iid); 
      }); 

});​ 

    #test { 
     color:white; 
     width: 400px; 
    height: 400px; 
    left: 200px; 
    background-color: #000; 
    position: absolute; 
    } 

    <div id="test">hover me please</div>​ 

或這裏小提琴: http://jsfiddle.net/qjxqC/1/

感謝您幫助

+0

其中是處理滾動事件的函數? – palerdot

回答

1

首先不附加JavaScript屬性(IID)到DOM參考的(這個)this.iid。這會在某些瀏覽器(IE)中導致內存泄漏。我也推薦一個遞歸超時。

我會爲此操作使用setTimeout。它提供了更多的控制,因爲您的限制檢查和更容易從您的功能中斷開。這裏是你的代碼重做。

$(document).ready(function(){ 
    var timeout; // keep your timeout reference at a higher scope for example 
    $('#test').bind({ 
     'mouseenter': function(){ 
      var self = $(this); 
      var incrementScroll = function() { 
       var left = parseInt(self.css("left")); 
       if(left <= 400) { 
        self.css("left", "+=200"); // as of jQuery 1.6 you can do this 
        // self.css("left", left+200); 
        timeout = setTimeout(incrementScroll, 525); 
       } 
      }    
      incrementScroll(); 
     }, 
     'mouseleave': function(){ 
      clearTimeout(timeout); 
    }}); 
}); 
1

更換

var self = $(this); 

通過

var self = this; 

因爲style是一個DOM對象,而不是jQuery對象的屬性,但你這樣做:

self.style.left = right + "px";