2013-09-16 63 views
1

我有三個圖像初始化一個精靈的形象,我想改變圖像位置每秒,而鼠標懸停在圖像懸停代碼每隔1秒

我已經試過:

$(".miniPosterImg").hover(function() { 
     setInterval(function() { 
      thismarginLeft = $(this).css("margin-left").replace(/[^0-9]/g, ''); 
      if (thismarginLeft < 360) { 
       thismarginLeft = thismarginLeft - 120; 
       //}else{ 
       //  thismarginLeft = 0; 
      } 
      $(this).css("margin-left", thismarginLeft + "px"); 
     }, 1000); 
    }); 

http://jsfiddle.net/377Ja/4/

+1

它有什麼問題? – Archer

+2

你確實意識到,如果你想改變懸停的位置,他們將不再被盤旋在上面,對吧? –

+0

發生了什麼?結果?你錯過了回調(clearInterval)? – Praveen

回答

2

我覺得你的代碼是持續重複。因此請在您的回調中加入clearInterval

但是小心,你需要使用可變像下面

var toggle; 
$(".miniPosterImg").hover(function() { 
    toggle = setInterval(function(){ 
     thismarginLeft = $(this).css("margin-left").replace(/[^0-9]/g,''); 
     if(thismarginLeft < 360){ 
       thismarginLeft = thismarginLeft-120; 
     //}else{ 
     //  thismarginLeft = 0; 
     } 
     $(this).css("margin-left", thismarginLeft + "px"); 
    },1000);}, 
    function(){ 
      clearInterval(toggle); 
    } 
}); 

更新您的評論:

最好有一個單獨的方法來處理setInterval這樣

tToggle = function() { 
    thismarginLeft = $('.miniPoster').css("marginLeft").replace(/[^0-9]/g,''); 
    if(thismarginLeft < 360){ 
      thismarginLeft = thismarginLeft-120;   
    } 
    $('.miniPoster').css("marginLeft", thismarginLeft + "px"); 
} 

然後像這樣使用

var toggle; 
$(".miniPosterImg").hover(function() { 
    toggle = setInterval(tToggle, 1000); 
}, 
function() { 
    clearInterval(toggle); 
}); 

而且FYI:

$('.miniPoster').css("margin-left") //WRONG 
$('.miniPoster').css("marginLeft") //CORRECT 

Working JSFIDDLE

+0

您需要在函數外部定義'var toggle'。否則,該變量將在回調中未定義:http://jsfiddle.net/377Ja/3/ – Alvaro

+0

@Alvaro我錯過了它。感謝您指出它。 – Praveen

+0

@ user1671639感謝您的良好道德:) –

1

你需要做懸停使用setInterval,然後鼠標了,你應該清除與clearInterval德區間。

生活演示:http://jsfiddle.net/377Ja/

var myInterval 

$(".miniPosterImg").hover(function() { 
    myInterval= setInterval(function(){ 
     thismarginLeft = $(this).css("margin-left").replace(/[^0-9]/g,''); 
     if(thismarginLeft < 360){ 
       thismarginLeft = thismarginLeft-120; 
     //}else{ 
     //  thismarginLeft = 0; 
     } 
     $(this).css("margin-left", thismarginLeft + "px"); 
    },1000); 
}, function(){ 
    clearInterval(myInterval) ; 
}); 
+0

不工作http://jsfiddle.net/377Ja/4/ – user2783132

+0

問題出在你的代碼中。不在我給的解決方案中。你不能使用'margin-left'。控制檯拋出一個錯誤...你應該使用'marginLeft'。 – Alvaro

+0

是什麼? '$(this).css(「marginLeft」,thismarginLeft +「px」);' – user2783132

1

既然你有一個精靈,我相信你要更改的屬性是後臺位置

試試這個:

.miniPosterImg:hover{ 
    /*only doing animation for chrome, use other prefixes to replicate in other browser*/ 
    -webkit-animation: slideImage 1s; 
    background:url(/*your url*/); 
} 

@-webkit-keyframes slideImage{ 
    0%{background-position: 0px 0px} 
    50%{background-position: -120px 0px} 
    100%{background-position: -240px 0px}  
}