實(shí)現(xiàn)鼠標(biāo)移動(dòng)改變圖片的透明度
所用知識(shí):
透明度屬性:opacity
setInterval()方法:設(shè)置時(shí)間函數(shù)
setInternal
clearInterval()方法:取消時(shí)間函數(shù)
clearInterval.png
實(shí)現(xiàn)效果
animation1.gif
實(shí)現(xiàn)方法:
定義圖像以及設(shè)置其初始化透明度屬性
<style>
#img{
opacity: 1;
}
</style>
<body>

</body>
設(shè)置鼠標(biāo)的移動(dòng)事件
window.onload = function () {
//檢查是否支持getElementById方法
if (! document.getElementById) return false;
//獲取到img元素
var img = document.getElementById("img");
//設(shè)置鼠標(biāo)移入事件
img.onmouseover = function () {
startMove(50)
};
//設(shè)置鼠標(biāo)移出事件
img.onmouseout = function () {
startMove(100)
}
};
設(shè)置時(shí)間函數(shù)
//定義一個(gè)time事件,以便取消時(shí)間事件
var timer = null;
//設(shè)置一個(gè)臨時(shí)變量,用來(lái)存取當(dāng)前img的透明度
var alpha = 0;
function startMove(target) {
//獲取到img元素
var img = document.getElementById("img");
//取消其他time事件,防止鼠標(biāo)多次的移入移出產(chǎn)生異常的效果
clearInterval(timer);
//設(shè)置time事件,每30ms執(zhí)行一次
timer = setInterval(function (){
var speed = 0;
//當(dāng)前透明度超過(guò)目標(biāo)值,則應(yīng)該減少,速度設(shè)置為負(fù)數(shù),否則速度設(shè)置為正數(shù)
if (alpha > target){
speed = -10;
} else {
speed = 10;
}
//達(dá)到目標(biāo)值時(shí),取消時(shí)間函數(shù)
if (alpha == target){
clearInterval(timer);
}
//否則,繼續(xù)改變透明度,并為img元素設(shè)置其屬性
else {
alpha += speed;
img.style.opacity = alpha / 100;
}
},30);
}
完整代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Animation</title>
<style>
#img{
opacity: 1;
}
</style>
<script>
window.onload = function () {
//檢查是否支持getElementById方法
if (! document.getElementById) return false;
//獲取到img元素
var img = document.getElementById("img");
//設(shè)置鼠標(biāo)移入事件
img.onmouseover = function () {
startMove(50)
};
//設(shè)置鼠標(biāo)移出事件
img.onmouseout = function () {
startMove(100)
}
};
//定義一個(gè)time事件,以便取消時(shí)間事件
var timer = null;
//設(shè)置一個(gè)臨時(shí)變量,用來(lái)存取當(dāng)前img的透明度
var alpha = 0;
function startMove(target) {
//獲取到img元素
var img = document.getElementById("img");
//取消其他time事件,防止鼠標(biāo)多次的移入移出產(chǎn)生異常的效果
clearInterval(timer);
//設(shè)置time事件,每30ms執(zhí)行一次
timer = setInterval(function (){
var speed = 0;
//當(dāng)前透明度超過(guò)目標(biāo)值,則應(yīng)該減少,速度設(shè)置為負(fù)數(shù),否則速度設(shè)置為正數(shù)
if (alpha > target){
speed = -10;
} else {
speed = 10;
}
//達(dá)到目標(biāo)值時(shí),取消時(shí)間函數(shù)
if (alpha == target){
clearInterval(timer);
}
//否則,繼續(xù)改變透明度,并為img元素設(shè)置其屬性
else {
alpha += speed;
img.style.opacity = alpha / 100;
}
},30);
}
</script>
</head>
<body>

</body>
</html>