2014-02-03 2 views
2

У меня есть HTML со следующей структурой:Как встряхнуть элемент каждые 5 секунд?

<li><a class="" href="?sort-by=popular">Barang Terpopuler</a></li> 

Как сделать этот трясти элемент (движение влево и вправо) каждые 5 секунд с помощью JQuery? Есть ли встроенная анимация для этого?

+0

Я не думает, что их будут построен в функции, но почему бы не setInterval с JQuery одушевленным. – Gaurav

+1

Вы можете использовать эффект [Shake jQuery UI Effect] (http://api.jqueryui.com/shake-effect/), а также 'setInterval', чтобы получить желаемый эффект! –

+0

Вы обновили свой вопрос, включив «перемещение влево и вправо»? Я не видел этого первого раза. Сожалею! –

ответ

2

Попробуйте следующее:

jQuery.fn.shake = function() { 
    this.each(function(i) { 
     $(this).css({ 
      "position" : "relative" 
     }); 
     for (var x = 1; x <= 3; x++) { 
      $(this).animate({ 
       left : -25 
      }, 10).animate({ 
       left : 0 
      }, 50).animate({ 
       left : 25 
      }, 10).animate({ 
       left : 0 
      }, 50); 
     } 
    }); 
    return this; 
} 
setInterval(function() { 
    $('li').shake(); 
}, 5000); 

Fiddle

+0

именно то, что мне было нужно – adit

2

Вы можете достичь этого, используя плагин, например, classyWiggle, который предлагает немного больше функциональных возможностей, чем прокатки свой собственный (который может или не может быть хорошая вещь).

После того, как вы включили плагин, вы даете такой элемент класса wiggle

<img class="wiggle" src="images/image1.jpg" /> 

Тогда вы:

$('.wiggle').wiggle(); 

Плагин имеет ряд опций, которые можно установить:

degrees - an Array object which outlines the cycle of rotation for a wiggle increment. 
delay - allows you to specify, in milliseconds, the delay between switching from one rotation degree to the next (see degrees). A higher number creates a slower "wiggle." 
limit - allows you to specify the maximum number of wiggles. 
randomStart - a boolean value which tells the plugin to start wiggling all matched elements at the same degree or a random one. 
onWiggle - an event that is fired off with the end of each wiggle. 
onWiggleStart - an event that is fired off when the wiggling effect first starts. 
onWiggleStop - an event that is fired off when the wiggling effect is stopped. 

А также три метода, которые вы можете позвонить:

start() - starts the wiggle effect. 
stop() - stops the wiggle effect. 
isWiggling() - a method that can be used to determine if the matched element is currently "wiggling." 

Вы могли бы это повторять каждые пять секунд, так как:

function wiggleForOneSecond(el){ 
    el.wiggle(); 
    setTimeout(function(){el.wiggle('stop')},1000) 
} 

setInterval(function(){wiggleForOneSecond($('.wiggle'))},5000); 

Fiddle

1

... пример с использованием чистых JS (не JQ);

HTML:

<li><a class="shakeit" href="?sort-by=popular">Barang Terpopuler</a></li> 

JS:

var interval; 
shakeit = function(element){ 
    element.style.display = "block"; 
    var x = -1; 
    interval = setInterval(function(){ 
     if(x == -1){ 
      element.style.marginLeft = "5px"; 
     }else{ 
      switch(x){ 
       case 0 : 
        element.style.marginLeft = "-5px"; 
       break; 
       case 1 : 
        element.style.marginLeft = "0px"; 
        element.style.marginTop = "5px"; 
       break; 
       case 2 : 
        element.style.marginTop = "-5px"; 
       break; 
       default : 
        element.style.marginTop = "0px"; 
        clearInterval(interval); 
      } 
     } 
     x++; 
    },50)  
} 

shakeit(document.getElementsByClassName("shakeit")[0]); 
setInterval(function(){ 
    shakeit(document.getElementsByClassName("shakeit")[0]); 
},5000); 

стельку пример: http://jsfiddle.net/fnx3a/1/

интегрирован с JQ:

$.fn.shakeit = function(obj){ 
    var interval; 
    set = $.extend({ 
     time : 5000, //interval 
     top : "3px", 
     bottom : "3px", 
     left : "3px", 
     right : "3px" 
    }, obj); 

    var shake = function(element){ 
     element.style.display = "block"; 
     var x = -1; 
     interval = setInterval(function(){ 
      if(x == -1){ 
       element.style.marginLeft = set.right; 
      }else{ 
       switch(x){ 
        case 0 : 
         element.style.marginLeft = "-"+set.left; 
        break; 
        case 1 : 
         element.style.marginLeft = "0px"; 
         element.style.marginTop = set.top; 
        break; 
        case 2 : 
         element.style.marginTop = "-"+set.bottom; 
        break; 
        default : 
         element.style.marginTop = "0px"; 
         clearInterval(interval); 
       } 
      } 
      x++; 
     },50); 
    } 

    return $(this).each(function(i,el){    
      shake(el); 
      setInterval(function(){ 
       shake(el); 
      },set.time); 
     }); 
} 
$(".shakeit").shakeit(); 

fidd ле http://jsfiddle.net/fnx3a/2/

:) наслаждаться

Смежные вопросы