前端js實現透明度動畫效果的代碼教程

這個效果的實現和我的上一篇博客一樣,主要還是應用setInterval(fun(),milltime); 其中fun() 是每隔milltime毫秒要執行的函數。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>透明度動畫</title>
</head>
<style type="text/css">
    *{
        padding: 0;
        margin: 0;
    }
    #p1{
        width: 200px;
        height: 200px;
        background-color: red;
        opacity: 0.3;
        filter: alpha(opacity=30);
    }
</style>
<body>
    <p id="p1">

    </p>
</body>
<script type="text/javascript">
    var p1 = document.getElementById("p1");
    p1.onmouseover = function(){
        startMove(100);
    }
    p1.onmouseout = function(){
        startMove(30);
    }
    var timer = null;
    var alpha = 30;

    var startMove = function(iTarget){
        clearInterval(timer);
        var speed = 0;
        if(iTarget > alpha){
            speed = 5;
        }else {
            speed = -5;
        }
        timer = setInterval(function(){
            if(alpha == iTarget){
                clearInterval(timer);
            }else {
                alpha += speed;
                p1.style.filter = 'alpha(opacity='+ alpha + ')';
                p1.style.opacity = alpha/100;
            }
        },30);
    }
</script>
</html>

You May Also Like