滑鼠懸浮實現抖動效果例項程式碼

antzone發表於2017-06-20

在不少的網頁中都有這樣的效果,當滑鼠放在某個元素的時候,此元素出現抖動效果,之所以使用這種效果也許是為了效果醒目或者說純粹是為了動感等等,具體目的我們們就不管了,下面就介紹一下如何實現此效果。

程式碼如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>滑鼠懸浮抖動效果-螞蟻部落</title>
<style type="text/css">
#thediv{
  position:relative; 
  width:100px;
  height:100px;
  background-color:red;
  left:100px; 
  top:100px;
}
</style>
<script type="text/javascript"> 
var type=["marginTop","marginLeft"];
var rangeN=10;
var timeout=20; 
function shake(obj,end){ 
  var range=Math.floor(Math.random()*rangeN); 
  var typN=Math.floor(Math.random()*type.length); 
  obj["style"][type[typN]]=""+range+"px"; 
  var shakeTimer=setTimeout(function(){shake(obj,end)},timeout); 
  obj[end]=function(){clearTimeout(shakeTimer)}; 
}  
window.onload=function(){
  var thediv=document.getElementById("thediv");
  thediv.onmouseover=function(){
    shake(this,'onmouseout')
  }
}
</script> 
</head>
<body> 
<div id="thediv"></div>
</body>
</html>

以上程式碼實現了抖動效果,程式碼比較簡單這裡就不多介紹了,如有問題可以跟帖留言。

相關閱讀:

(1).Math.floor()參閱javascript Math.floor()一章節。

(2).Math.random()參閱javascript Math.random()一章節。 

(3).setTimeout()參閱window setTimeout()一章節。

(4).clearTimeout()參閱window clearTimeout()一章節。

相關文章