jQuery抖動效果詳解

admin發表於2017-11-25

本章節分享一段程式碼例項,它實現了元素的抖動效果,需要的朋友可以做一下參考。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css"> 
body{
  font-family:"Lucida Grande", Arial, Helvetica, sans-serif;
  color:#666666;
  font-size:12px;
  background:#FFFFFF;
  margin:20px;
  padding:20px;
}  
.block{
  float:left;
  border:1px solid #CCCCCC;
  background:#F0F0F0;
  padding:10px;
  margin:10px;
  width:200px;
} 
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript"> 
(function($){ 
  var element = {}; 
  $.fn.jshaker = function(){
    element = this; 
    element.css("position", "relative");
    element.find("*").each(function(i, el){ 
      $(el).css("position", "relative"); 
    }); 
    $.fn.jshaker.animate(element); 
  }; 
   
  $.fn.jshaker.animate = function(el){ 
    $.fn.jshaker.shake(el); 
    el.find("*").each(function(i, el){ 
      $.fn.jshaker.shake(el); 
    });
    var iFunc = function(){ 
      $.fn.jshaker.animate(el); 
    }; 
    setTimeout(iFunc, 50); 
  } 
   
  $.fn.jshaker.shake = function(el){ 
    if(Math.random() > 0.5){ 
      $(el).css("top",Math.random() * 20); 
    } 
    else{ 
      $(el).css("left", Math.random() * 20); 
    } 
  } 
})(jQuery); 
</script>
<script type="text/javascript"> 
$(document).ready(function(){ 
  $(".block").click(function(){ 
    $(this).jshaker(); 
  }); 
}); 
</script>
</head>
<body>
<div class="block">
  <p>點選本框內,可實現震動</p>
  <ul>
    <li>螞蟻部落一</li>
    <li>softwhy.com</li>
    <li>antzone</li>
  </ul>
</div>
</body>
</html>

上面的程式碼實現了我們的要求,下面介紹一下它的實現過程。

一.程式碼註釋:

(1).(function($){}),當文件結構完全載入完畢再去執行函式中的程式碼。

(2).var element = {},宣告一個變數,它是用來儲存jQuery物件的。

(3).$.fn.jshaker = function(){},此方法實現抖動效果。

(4).element = this,將當前jQuery物件賦值給變數。

(5).element.css("position", "relative"),將jQuery物件中的所有元素都設定為相對定位。

(6).element.find("*").each(function(i, el){ 

  $(el).css("position", "relative"); 

}),獲取所有的後代元素,並且通過each()遍歷的方式將其設定為相對定位。

(7).$.fn.jshaker.animate(element),此方法的作用會在後面介紹。

(8).$.fn.jshaker.animate = function(el){},此方法可以通過遞迴可以將所有元素不停的抖動,引數是一個jQuery物件。

(9).$.fn.jshaker.shake(el),此方法可以讓元素進行一次位移,連續的位移其實就是抖動。

(10).el.find("*").each(function(i, el){ 

  $.fn.jshaker.shake(el); 

}),實現所有的子元素都進行一次位移。

(11).var iFunc = function(){ 

  $.fn.jshaker.animate(el); 

},此方法本身,就是進行了一下包裝。

(12).setTimeout(iFunc, 50),遞迴方法不斷呼叫,那麼所有元素都不停的抖動起來。

(13).$.fn.jshaker.shake = function(el){ 

  if(Math.random() > 0.5){ 

    $(el).css("top",Math.random() * 20); 

  } 

  else{ 

    $(el).css("left", Math.random() * 20); 

  } 

} ,此方法實現了元素的位移效果。

抖動的幅度是0-20畫素。

二.相關閱讀:

(1).$.fn可以參閱jQuery.fn的作用是什麼一章節。

(2).css()可以參閱jQuery css()一章節。

(3).find()可以參閱jQuery find()一章節。

(4).each()可以參閱jQuery each()一章節。

(5).setTimeout()可以參閱setTimeout()一章節。

(6).Math.random()方法可以參閱javascript Math.random()一章節。

相關文章