使用这个 javascript 函数作为一个很好的淡入淡出效果:
function fade(element) {
var op = 1; // initial opacity
var timer = setInterval(function () {
if (op <= 0.1){
clearInterval(timer);
element.style.display = 'none';
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op -= op * 0.1;
}, 50);
}
这是我编写的用于淡入图像的示例实现:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript">
function fadeout(element) {
var op = 1; // initial opacity
var timer = setInterval(function () {
if (op <= 0.1) {
clearInterval(timer);
element.style.display = 'none';
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op -= op * 0.1;
}, 50);
}
function fadein(element) {
var op = 0.1; // initial opacity
var intimer = setInterval(function () {
if (op >= 1) {
clearInterval(intimer);
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
if (op == 0.1) {
element.style.display = 'block';
}
op += op * 0.1;
}, 50);
}
var images = [];
var counter = 0;
var state = 0;
function initimages() {
images[0] = document.getElementById("img1");
images[1] = document.getElementById("img2");
images[2] = document.getElementById("img3");
for (i = 1; i < images.length; i++) {
images[i].style.display = 'none';
}
}
function previous() {
if (state == 0) {
state = 1;
fadeout(images[counter]);
counter -= 1;
if (counter < 0) {
counter = images.length - 1;
}
setTimeout(function () {
fadein(images[counter]);
}, 1300);
setTimeout(function () {
state = 0;
}, 2500);
}
}
function next() {
if (state == 0) {
state = 1;
fadeout(images[counter]);
counter += 1;
if (counter >= images.length) {
counter = 0;
}
setTimeout(function () {
fadein(images[counter]);
}, 1300);
setTimeout(function () {
state = 0;
}, 2500);
}
}
</script>
<style type="text/css">
div.imgcontainer {
height:100px;
width:200px;
background-color:#CCC;
padding:50px 0px;
}
div.imgcontainer img {
background-color:#FFF;
width: 100px;
height:100px;
}
</style>
<title></title>
</head>
<body onload="initimages();">
<div class="imgcontainer">
<center>
<img alt="1" id="img1" name="img1" src="">
<img alt="2" id="img2" name="img2" src="">
<img alt="3" id="img3" name="img3" src="">
</center>
</div>
<input onclick="previous();" type="button" value="Previous">
<input onclick="next();" type="button" value="Next">
</body>
</html>
祝你好运!