1. 程式人生 > >HTML+CSS+JS實現透明度動畫

HTML+CSS+JS實現透明度動畫

1.box.html程式碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>廣告</title>
    <link rel="stylesheet" type="text/css" href="box.css"/>
    <script src="box.js"></script>
</head>

<body>
<div id="box">
</div>
</body>

</html>

2.box.css程式碼:
body {
    padding: 0px;
    margin: 0px;
}

#box {
    height: 200px;
    width: 200px;
    background-color: rebeccapurple;
    -webkit-border-radius: 5%;
    -moz-border-radius: 5%;
    border-radius: 5%;
    -ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=30);
    filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=30);
    opacity: 0.3;
}

3.box.js程式碼:
window.onload = function () {
    var box = document.getElementById('box');
    box.onmouseover = function () {
        move(100);
    }
    box.onmouseout = function () {
        move(30);
    }
}
var timer = null;
var alpha = 30;

function move(target) {
    var box = document.getElementById('box');
    clearInterval(timer);
    timer = setInterval(function () {
        var speed = 0;
        if (alpha > target) {
            speed = -10;
        } else {
            speed = 10;
        }
        if (alpha == target) {
            clearInterval(timer);
        } else {
            alpha += speed;
            box.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(Opacity=' + alpha + ')';
            box.style.opacity = alpha / 100;
        }
    }, 30);
}