一张图片的淡入淡出##
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.img01{
width: 400px;
height: 400px;
opacity: 0.3;
filter: alpha(opacity=30);
}
</style>
</head>
<body>
<img class="img01" id="img01" src="1.jpg" alt="">
<script>
/**
* 使用js匀速运动实现图片的淡入淡出效果
* 这里没有使用变量而是用了一个更麻烦的方法。其中遇到种种的问题
* 出错问题点:
* 1、首先使用getStyle获得行内样式的opacity,注意点这个获得的alpha值其实是一个字符串类型,要转为数值型
* 2、特别要注意在将值付给opactiy就要这里有一个小数精确的问题: 例如0.1+0.2不等于0.3,解决这个问题可以分别先*10,在除以10
* 3、timer 原先被我定义在startMove中。当快速移入的时候就会出现闪屏的问题。需要把timer移到外面来。
*/
window.onload = function () {
var oImg = document.getElementById('img01');
var alpha = Number(getStyle(oImg,"opacity"));
oImg.onmouseover = function () {
startMove(1);
};
oImg.onmouseout = function () {
startMove(0.3);
};
var timer = null;
function startMove (iTarget) {
var oImg = document.getElementById('img01');
clearInterval(timer);
timer = setInterval(function(){
var speed = 0;
if( alpha < iTarget ) {
speed = 0.1;
}else{
speed = -0.1;
}
if(alpha === iTarget){
clearInterval(timer);
}else{
alpha = (alpha*10 + speed*10)/10;
oImg.style.opacity = alpha;
oImg.style.filter = "alpha(opacity="+ alpha*100 +")";
}
},30);
}
function getStyle (obj, attr) {
if(window.getComputedStyle){
return window.getComputedStyle(obj,null)[attr];
}else{
return obj.currentStyle[attr];
}
}
};
</script>
</body>
</html>
多个图片淡入淡出##
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
ul,li{
list-style: none;
}
.imglist {
width: 1000px;
height: 400px;
}
.imglist ul {
width: 1000px;
overflow: hidden;
}
.imglist ul li.item {
width: 200px;
height: 400px;
float: left;
opacity: 0.3;
filter: alpha(opacity=30);
}
.imglist ul li.item img {
width: 200px;
height: 400px;
float: left;
}
</style>
</head>
<body>
<div class="imglist">
<ul id="imglist">
<li class="item i1"><img src="1.jpg" alt=""></li>
<li class="item i2"><img src="1.jpg" alt=""></li>
<li class="item i3"><img src="1.jpg" alt=""></li>
<li class="item i4"><img src="1.jpg" alt=""></li>
<li class="item i5"><img src="1.jpg" alt=""></li>
</ul>
</div>
<script>
window.onload = function () {
var oImg = document.getElementById('imglist');
var oImgLi = oImg.getElementsByTagName('li');
//ES5的func
Array.prototype.forEach.call(oImgLi, function (img) {//传递回调函数,构建新的作用域
//timer、alpha和startMove,不应该被每个li共享使用,因为每个li都有自己的状态,自己的动画状态(自己的动画时长,alpha透明度)
var timer = null,
alpha = 0.3;
function startMove(obj, iTarget) {
clearInterval(timer);
timer = setInterval(function () {
var speed = 0;
if (alpha < iTarget) {
speed = 0.1;
} else {
speed = -0.1;
}
if (alpha === iTarget) {
clearInterval(timer);
} else {
alpha = (alpha * 10 + speed * 10) / 10;
obj.style.opacity = alpha;
obj.style.filter = "alpha(opacity=" + alpha * 100 + ")";
}
}, 30);
}
img.onmouseover = function () {
startMove(this, 1);
};
img.onmouseout = function () {
startMove(this, 0.3);
};
});
};
</script>
</body>
</html>