是否可以在使用 setInterval() 函数更改的图像之间进行转换?

Is it possible to put transition between images changing with setInterval() function?

现在图像只是一张一张地切换,我希望在图像因用户体验而改变时添加某种过渡。

在 HTML 中看起来是这样的:

<img id="image" src="img5.png" style="width:100%">

脚本如下所示:

var imageSources = ["img1.png", "img2.png", "img3.png", "img4.png", "img5.png"]

var index = 0;
setInterval (function(){
  if (index === imageSources.length) {
    index = 0;
  }
  document.getElementById("image").src = imageSources[index];
    index++;
} , 2000);

我已经为你制定了解决方案:

<img id="myimage" src="http://www.dumpaday.com/wp-content/uploads/2019/12/1-45.jpg">
<script>
var images = [
    "http://www.dumpaday.com/wp-content/uploads/2019/12/1-45.jpg",
    "http://www.dumpaday.com/wp-content/uploads/2019/12/2-73.jpg",
    "http://www.dumpaday.com/wp-content/uploads/2019/12/3-66.jpg"
];
var index = 0;
var myImage = document.getElementById("myimage");
var i = 0;
setInterval(function() {
    if (++i % 2) {
        myImage.style.opacity = 0.1;
    } else {
        myImage.src = images[index = (index + 1) % images.length];
        myImage.style.opacity = 1;
    }
}, 2000);
</script>
<style>
    img {
      transition: opacity 1s;
    }
</style>

注意样式。

Fiddle: https://jsfiddle.net/m3rxwbdv/

https://jsfiddle.net/4qox2d1p/4/

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .img {
            transition: 1s all;
        }
    </style>
</head>
<body>
    <div id="container"></div>
    <script>
        const sources = [
        'http://placeimg.com/640/480/arch/1',
        'http://placeimg.com/640/480/arch/2',
        'http://placeimg.com/640/480/arch/3',
        'http://placeimg.com/640/480/arch/4',
        'http://placeimg.com/640/480/arch/5',
        ]
        const container = document.getElementById('container')
        const images = sources.map(source => {
          const img = document.createElement('img')
          img.style.opacity = 0;
          img.style.position = 'absolute'
          img.classList.add('img')
          img.src = source
          container.appendChild(img)
          return img
        })

        images[0].style.opacity = 1
        let current = 0
        setInterval(() => {
          images.forEach((image, index) => {
            image.style.opacity = index === current ? 1 : 0
          })
          current++
          if (current > sources.length - 1) current = 0
        }, 1000)

    </script>
</body>
</html>