1

私は 3 つの画像 init を持つスプライト画像を持っています。マウスが画像の上にある間、毎秒画像の位置を変更したいと思います。

私が試したこと:

  $(".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/

4

3 に答える 3

2

コードが継続的に繰り返されていると思います。したがって、 callbackを追加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);
});

参考までに:

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

働くJSFIDDLE

于 2013-09-16T15:33:20.447 に答える
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) ;
});
于 2013-09-16T15:31:54.523 に答える
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}       
}
于 2013-09-16T15:45:11.600 に答える