DIV CSS 佈局教程網

用JS實現鼠標懸停時圖片抖動的效果
編輯:關於JavaScript     

本文為大家分享一個俏皮的小特效:當鼠標移到圖片上時,圖片會像發抖一樣左右上下快速晃動,移開後又恢復平靜。它能為頁面增添一份活潑的互動趣味。

實現思路

效果的關鍵是「位置偏移」。鼠標移入時啟動一個定時器,讓圖片的 top 與 left 值按順序在「下、右、上、左」四個方向不斷微調,從而形成高頻抖動的錯覺;抖動幅度由變量 rector 控制,數值越大晃得越厲害。鼠標移出時則把停止標記置位,並將圖片位置歸零复位。

完整代碼如下:

<html>
<head>
<title>鼠標觸發圖片抖動效果</title>
<style>
.shakeimage{
position:relative
}
</style>
<script language="JavaScript1.2">
var rector=3
var stopit=0
var a=1
function init(which){
stopit=0
shake=which
shake.style.left=0
shake.style.top=0
}
function rattleimage(){
if ((!document.all&&!document.getElementById)||stopit==1)
return
if (a==1){
shake.style.top=parseInt(shake.style.top)+rector
}
else if (a==2){
shake.style.left=parseInt(shake.style.left)+rector
}
else if (a==3){
shake.style.top=parseInt(shake.style.top)-rector
}
else{
shake.style.left=parseInt(shake.style.left)-rector
}
if (a<4)
a++
else
a=1
setTimeout("rattleimage()",50)
}
function stoprattle(which){
stopit=1
which.style.left=0
which.style.top=0
}
</script>
</head>
<body bgcolor="#F7F7F7">
<p align="center">
<img src=/images/skinslogo.gif class="shakeimage" onMouseover="init(this);rattleimage()" onMouseout="stoprattle(this)">
<br>
鼠標移動上來看效果!</p>
</body>
</html>

以上就是本次分享的全部內容,希望對大家的 JavaScript 開發有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved