Зацикливание кода при наведении курсора на JavaScript с помощью jQuery - PullRequest
2 голосов
/ 13 октября 2010

Я хочу запустить и остановить цикл с заданной задержкой с помощью события наведения курсора jQuery. Я пытался сделать это с помощью «mouseover» и «mouseout» без удачи.

Пример (нечетный псевдокод):

Mouseover
    Loop
        Change text colour
        Wait 100ms
Mouseout
    Stop loop

Я уверен, что это очень просто, я просто не знаю, как структурировать его с помощью JavaScript.

Заранее спасибо.

Ответы [ 4 ]

1 голос
/ 13 октября 2010
function rgb() {
    var color = 'rgb(';
    for (var i = 0; i < 3; i++) {
        color += Math.floor(Math.random() * 255) + ',';
    }
    return color.replace(/\,$/, ')')
}

var loop = null;
$(function () {
    $('#someid').hover(function () {
        var $this = $(this);
        loop = setInterval(function () {
            $this.css({backgroundColor: rgb() });
        }, 100);
    }, function () {
        clearInterval(loop);
    });
});

попробуйте пример: http://jsbin.com/uraxe4

1 голос
/ 13 октября 2010

Это может сработать:

$(function(){
    $('#test').hover(function(){
      var self = $(this),
         rnd  = null,
         col  = null;

      this.iid = setInterval(function(){          
        col = ['#'];
        rnd = ~~(Math.random()*255);
          col.push(rnd.toString(16).length < 2 ? '0' + rnd.toString(16) : rnd.toString(16));     
          col.push(rnd.toString(16).length < 2 ? '0' + rnd.toString(16) : rnd.toString(16));
          col.push(rnd.toString(16).length < 2 ? '0' + rnd.toString(16) : rnd.toString(16));

        self.css({backgroundColor: col.join('')});
      }, 100);
   }, function(){
       if(this.iid){
           clearInterval(this.iid);
           delete this.iid;
       }
  });
});​

Смотрите это в действии: http://www.jsfiddle.net/YjC6y/19/

0 голосов
/ 13 октября 2010
changeColorTimerId = -1;


$('.box').hover(function(){
  //mouseOver code here
   changeColorTimerId = setInterval ( changeColor, 1000 );  
},function(){
  //mouseOut  code here  
  if ( changeColorTimerId ){
      clearInterval ( changeColorTimerId  )
  }

});

function changeColor(){
  $(".box").css ( 'backgroundColor',  '' + getRandomColor() );
}

function getRandomColor(){  
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.round(Math.random() * 15)];
    }
    return color;
}

рабочий пример здесь:

http://jsbin.com/etogi3/2

0 голосов
/ 13 октября 2010
$("#yourElem").hover(
  function () {  /* mousenter */
    $this = $(this);

    // take note that the mouse is currently hovering
    $this.data("isHovering", true);

    // create an interval and store its ID in jQuery data
    $this.data("loopId", setInterval(function () {
      // only do something if we are still hovering
      if ($this.data("isHovering")) {
        $this.css("color", getRandomColorValue());
      }
    }, 100);
  },
  function () {  /* mouseleave */
    $this = $(this);

    // take note that the mouse is no longer hovering
    $this.data("isHovering", false);

    // clear the interval that was set and delete the ID
    if ($this.data("loopId")) {
      clearInterval($this.data("loopId"));
      $this.data("loopId", false);
    }
  }
)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...