1

所以这是我的幻灯片 div:

<div class="header">
    <img name="slide" class="slide">
</div>

它的CSS:

.slide{
    width: 80%;
    height: auto;
    filter: brightness(90%);
}

和javascript:

var i = 0;
var images = [];
var time = 4000;


images[0] = '1.png';
images[1] = '2.png';
images[2] = '3.png';

function changeImg() {
  document.slide.src = images[i];

  if (i < images.length -1) {
    i++;

  }
  else
  {
    i = 0;
  }


  setTimeout("changeImg()", time);

}

window.onload = changeImg;

现在我希望它交叉淡入淡出,目前它只是非常突然地切换图像,但我希望它平滑。有什么帮助吗?

4

2 回答 2

1

您需要在您的 css 类上添加 opacity 设置为 0,然后创建一个 opacity 设置为 1 的新类,这样您将触发函数在特定时间段过去后切换不透明度

<style>
    .slide {
        border: none; 
        opacity: 0; 
        position: absolute; 
        top: 0; 
        left: 0;
        -webkit-transition: opacity 2s linear;
        -moz-transition: opacity 2s linear;
        -o-transition: opacity 2s linear;
        transition: opacity 2s linear;
    }
    .visible {
        opacity: 1;
    }
</style>

<div class="header">
    <img id="img0" class="slide visible" src="1.png">
    <img id="img1" class="slide" src="2.png">
    <img id="img2" class="slide" src="3.png">
</div>

<script>
    var actual = 0;
    var total = 3;

    function addClass(elem, name) {
        elem.className = elem.className + " " + name;
    }

    function deleteClass(elem, name) {
        var c = elem.className;
        elem.className = c.replace(name, "").replace(/   /g, " ").replace(/^ | $/g, "");
    }

    function nextImg() {
        var e;

        e = document.getElementById("img" + actual);
        deleteClass(e, "visible");

        actual++;
        if (actual > total - 1) actual = 0;

        e = document.getElementById("img" + actual);
        addClass(e, "visible");
    }

    var slider = setInterval(nextImg, 4000);
</script>
于 2018-09-21T14:31:03.550 回答
1

虽然我喜欢 Joe 的回答,但这是一个使用 JavaScript 而不添加或删除类的答案:

<img>为了便于参考,我在这里给出了一个 id:

<img id='slideShow' name="slide" class="slide">

JavaScript:

function fadeImg(elem, total, step, speed){ 
    step=step||5;
    speed=speed||50;
    var iter=0;
    var fadeOutTime=(100/step)*speed;
    var time=total;
    var n = 0;
    var opacity;
    elem.src=images[n];
    var fadeInterval=setInterval(function(){
        time=time-speed;
        opacity=iter/100;
        if(time>fadeOutTime&&opacity<1){
            iter=iter+step;
        } else if(time<=fadeOutTime&&time>0&&opacity>0){
            iter=iter-step;
        } else if(time<=0){
            n<images.length-1?n++:n=0;
            elem.src=images[n];
            time=total;
        }
        elem.style.opacity=opacity;
        elem.style.filter= 'alpha(opacity=' +opacity*100 + ')';
    },speed);
}

window.onload = fadeImg(document.getElementById('slideShow'),time);

我从这里借用了区间概念:https ://stackoverflow.com/a/2207751/6661052

于 2018-09-21T16:04:08.830 回答