幻灯片放映淡化效果令人陶醉

时间:2016-12-28 20:46:27

标签: javascript jquery html css

我的图像滑块工作,但第一次图像旋转时,一个图像抖动。在接下来的传球上它很顺利吗?

Javascript代码。

var imgArray = [
   'about.jpg',
   'about2.jpg',
   'about3.jpg'],
   curIndex = 0;
   imgDuration = 5000;

function slideShow() {
   document.getElementById('slider').className += "fadeOut";
   setTimeout(function() {
       document.getElementById('slider').src = imgArray[curIndex];
       document.getElementById('slider').className = "";
   },1000);
   curIndex++;
   if (curIndex == imgArray.length) { curIndex = 0; }
      setTimeout(slideShow, imgDuration);
}
slideShow();

CSS代码。

#slider {
   opacity:1;
   transition: opacity 1s;
   float:left;
   max-width:100%;
   height:auto;
   margin-right:20px;
   border-radius:4px 4px 4px 4px;
   border-color:#CCC;
   border-style:ridge;
   border-width:2px; 
}

#slider.fadeOut {
   opacity:0;
}

我的网站。 See the effect on my site

这是唯一涉及的HTML。

img id="slider" src="images/other-images/blank.jpg"

您可以使用您的代码查看网站。 Test Site

1 个答案:

答案 0 :(得分:0)

这是因为图片加载。

你可以创建一个如下所示的jquery插件:

$.fn.preload = function() {
    this.each(function(){
        $('<img/>')[0].src = this;
    });
}

$(['about.jpg','about2.jpg','about3.jpg']).preload();

所以你的代码最终会像这样:

$.fn.preload = function() {
    this.each(function(){
        $('<img/>')[0].src = this;
    });
}

var imgArray = [
'about.jpg',
'about2.jpg',
'about3.jpg'],
curIndex = 0;
imgDuration = 5000;

imgArray.preload();

function slideShow() {
    document.getElementById('slider').className += "fadeOut";
    setTimeout(function() {
        document.getElementById('slider').src = imgArray[curIndex];
        document.getElementById('slider').className = "";
    },1000);
    curIndex++;
    if (curIndex == imgArray.length) { curIndex = 0; }
    setTimeout(slideShow, imgDuration);
}
slideShow();

我没有测试,但这表明你需要先预装图像。

我喜欢使用的一个库是Owl Carousel,它非常容易安装和使用。使用https://owlcarousel2.github.io/OwlCarousel2/

修改 只需确保在以下位置正确引用图像:

var imgArray = [
'about.jpg',
'about2.jpg',
'about3.jpg']

所以这可能是:

var imgArray = [
'/path/to/about.jpg',
'/path/to/about2.jpg',
'/path/to/about3.jpg']