背景图像平滑变化

时间:2017-09-28 09:15:40

标签: javascript html css

我尝试了很多东西来改变背景图像,但没有任何效果。也许有人可以帮我在我的javascript中实现一些淡入淡出效果?或者只是告诉我如何简单地添加效果?

我的javascript

var imageID=0;
function changeimage(every_seconds){
    //change the image
    if(!imageID){
        document.getElementById("myimage").src="./assets/imagesVR/VR_bg.jpg";
        imageID++;
    }
    else{if(imageID==1){
        document.getElementById("myimage").src="./assets/imagesVR/_DSC5362.jpg";
        imageID++;
    }else{if(imageID==2){
        document.getElementById("myimage").src="./assets/imagesVR/_DSC5178.jpg";
        imageID=0;
    }}}
    //call same function again for x of seconds
    setTimeout("changeimage("+every_seconds+")",((every_seconds)*1000));
}

我的HTML

<div id="sliderB" id='myimage'><img style="width:100%;height:100%;"  id='myimage' /></div>

我的Css

/* New Options */
    #sliderB {
        position:absolute;
        width:100%;
        height:100%;
        left:0px;
        top:0px;
        background-size: cover;

    }

感谢并抱歉语言不好,而不是我的母语。

2 个答案:

答案 0 :(得分:1)

你可以尝试一些不透明的东西,同时将一个图像放在另一个上:

var imgId = 0;

function change_image() {
  document.querySelectorAll('.slide')[imgId].className = "slide";
  imgId++;
  if (imgId == 4)
    imgId = 0;
  document.querySelectorAll('.slide')[imgId].className = "slide active";

  setTimeout(function() {
    change_image()
  }, 3000);
}

setTimeout(function() {
  change_image()
}, 3000);
.slider {
  position: relative;
  width: 300px;
  height: 300px;
}

.slider .slide {
  position: absolute;
  background-size: 100% 100%;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  opacity: 0;
  transition: 2s;
}

.slider .slide.active {
  opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slider">
  <div class="slide active" style="background-image:url(https://lorempixel.com/300/300/)"></div>
  <div class="slide" style="background-image:url(https://lorempixel.com/300/200/)"></div>
  <div class="slide" style="background-image:url(https://lorempixel.com/200/300/)"></div>
  <div class="slide" style="background-image:url(https://lorempixel.com/300/100/)"></div>
</div>

我们的想法是将有效类从一张幻灯片更改为另一张幻灯片,并且通过CSS过渡,您将获得淡入淡出

答案 1 :(得分:-1)

我希望它会有所帮助

请更改css样式,如下所示

#sliderB 
{
    position:absolute;
    width:100%;
    height:100%;
    left:0px;
    top:0px;
    background-size: 100% auto;
}