JS实现图片的淡入淡出(实战中将div换成图片即可)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
#b1,
#b2,
#b3 {
width: 100px;
height: 100px;
background: deepskyblue;
opacity: 0.3;
}
#b2 {
background: palevioletred;
margin: 10px 0;
}
</style>
</head>
<body>
<div id="b1"></div>
<div id="b2"></div>
<div id="b3"></div>
<script>
var oDiv = document.querySelectorAll('div');
for (var i = 0; i < oDiv.length; i++) {
oDiv[i].alpha = 30;
oDiv[i].onmouseover = function () {
move(this, 100)
}
oDiv[i].onmouseout = function () {
move(this, 30)
}
}
function move(obj, index) {
var times = '';
clearInterval(times);
times = setInterval(() => {
var speed = index - obj.alpha > 0 ? 1 : -1;
if (index == obj.alpha) {
clearInterval(times);
} else {
obj.alpha += speed;
obj.style.opacity = obj.alpha / 100;
}
}, 30);
}
</script>
</body>
</html>```