淡入淡出轮播图自动_CSSFadey:自动淡入图像库

淡入淡出轮播图自动

Some time ago I wrote a small script that automated the process of creating a responsive image carousel. While the same result could be achieved using pure CSS, doing so required that keyframes had to be recalculated when the number of images changed. Written in pure , my solution retained the performance advantages of by writing a keyframe animation using a wide range of options.

前段时间,我编写了一个小脚本,该脚本使创建响应式图像轮播的过程自动化 。 尽管使用纯CSS可以实现相同的结果 ,但是这样做需要在图像数量更改时必须重新计算关键帧。 我的解决方案使用纯 ,通过使用多种选项编写关键帧动画来保留的性能优势。

The script presented here accomplishes a similar result, only with a fade-in sequence: again, you can add as many images as you like, in the order you wish. The only requirement is that that all the images must be all the same size:

此处显示的脚本仅用淡入顺序即可达到相似的结果:同样,您可以根据需要添加任意数量的图像。 唯一的要求是所有图像都必须具有相同的大小:

<figure id="fadey">
    <img src="dancer-arch.jpg" alt>
    <img src="white-bridge-jump.jpg" alt>
    <img src="dancer-beams.jpg" alt>
    <img src="bridge-white-walker.jpg" alt>
</figure>

Naturally, the alt values should be completed for each image; they’ve been left blank here in order to save space.

当然,应该为每个图像完成alt ; 为了节省空间,此处将它们留空。

I’d advise using srcset, the w descriptor and the sizes attribute for each image to achieve the best results:

我建议使用srcsetw描述符和每个图像sizes属性来达到最佳效果:

<img src="dancer-arch.jpg"
srcset="dancer-arch.jpg 750w, dancer-arch-2x.jpg 1500w" 
sizes="(min-width: 750px) 750px, 100vw">

There’s also some basic CSS that is used to format the images and gallery container:

还有一些用于格式化图像和图库容器的基本CSS:

#fadey { 
    width: 100%; 
    position: relative;
}
#fadey img {
    display: block;
    width: 100%;
}

#fadey must be 100% of the width of its container. If #fadey is a figure element, left margin should be set to 0:

#fadey必须是其容器宽度的100%。 如果#fadeyfigure元素,则left margin应设置为0:

margin: 0 auto

The script is added at the end of the page:

该脚本被添加到页面的末尾:

var cssFadey = function(newOptions) {
    var options = (function() {
        var mergedOptions = {},
        defaultOptions = {
            presentationTime: 3,
            durationTime: 2,
            fadeySelector: '#fadey',
            cssAnimationName: 'fadey',
            fallbackFunction: function() {}
        };
        for (var option in defaultOptions) mergedOptions[option] = defaultOptions[option];
        for (var option in newOptions) mergedOptions[option] = newOptions[option];
        return mergedOptions;
    })(),
    CS = this;
    CS.animationString = 'animation';
    CS.hasAnimation = false;
    CS.keyframeprefix = '';
    CS.domPrefixes = 'Webkit Moz O Khtml'.split(' ');
    CS.pfx = '';
    CS.element = document.getElementById(options.fadeySelector.replace('#', ''));
    CS.init = (function() {
        if (CS.element.style.animationName !== undefined) CS.hasAnimation = true;
        if (CS.hasAnimation === false) {
            for (var i = 0; i < CS.domPrefixes.length; i++) {
                if (CS.element.style[CS.domPrefixes[i] + 'AnimationName'] !== undefined) {
                    CS.pfx = domPrefixes[i];
                    CS.animationString = pfx + 'Animation';
                    CS.keyframeprefix = '-' + pfx.toLowerCase() + '-';
                    CS.hasAnimation = true;
                    break;
                }
            }
        }
        if (CS.hasAnimation === true) {
			function loaded() { 
				var imgAspectRatio = firstImage.naturalHeight / (firstImage.naturalWidth / 100);   
				var imageCount = CS.element.getElementsByTagName("img").length,
				totalTime = (options.presentationTime + options.durationTime) * imageCount, 
				css = document.createElement("style"); 
				css.type = "text/css";
	            css.id = options.fadeySelector.replace('#', '') + "-css";
	            css.innerHTML += "@" + keyframeprefix + "keyframes " + options.cssAnimationName + " {\n";
	            css.innerHTML += "0% { opacity: 1; }\n";
	            css.innerHTML += (options.presentationTime / totalTime) * 100+"% { opacity: 1; }\n";
	            css.innerHTML += (1/imageCount)*100+"% { opacity: 0; }\n";
	            css.innerHTML += (100-(options.durationTime/totalTime*100))+"% { opacity: 0; }\n";
	            css.innerHTML += "100% { opacity: 1; }\n";
  css.innerHTML += "}\n";
	            css.innerHTML += options.fadeySelector + " img { position: absolute; top: 0; left: 0; " + keyframeprefix + "animation: " + options.cssAnimationName + " " + totalTime + "s ease-in-out infinite; }\n";
	          css.innerHTML += options.fadeySelector + "{ box-sizing: border-box; padding-bottom: " + imgAspectRatio + "%; }\n";
	          for (var i=0; i < imageCount; i++) {
	            css.innerHTML += options.fadeySelector + " img:nth-last-child("+(i+1)+") { " + keyframeprefix + "animation-delay: "+ i * (options.durationTime + options.presentationTime) + "s; }\n";
	            }
			document.body.appendChild(css); 
		}
		var firstImage = CS.element.getElementsByTagName("img")[0];
		if (firstImage.complete) {
			loaded();
		} else {
			firstImage.addEventListener('load', loaded);
			firstImage.addEventListener('error', function() {
				alert('error');
			})
		}
	} else {
		// fallback function
		options.fallbackFunction();
        }
    })();
}

The script is called with:

该脚本的调用方式为:

cssFadey();

There are several possible options when you call the function, which I’ll cover in a moment. A quick explanation of the defaults:

调用该函数时,有几种可能的选择,我将在稍后介绍。 默认值的简要说明:

  • presentationTime is the amount time each image appears on screen, measured in seconds (three seconds, by default)

    presentationTime是每个图像在屏幕上出现的时间,以秒为单位(默认为三秒)

  • transitionTime is the time of the fade between each image, also measured in seconds (two seconds, by default)

    transitionTime是每个图像之间的淡入时间,也以秒为单位(默认为2秒)

  • fadeySelector is the id of the element that contains the images (by default this is a <figure> element with an id of fadey, although the element and id used is up to you

    fadeySelector是包含图像的元素id (默认情况下,这是一个<figure>元素,其idfadey ,尽管所用的元素和id取决于您

  • cssAnimationName is the name of the keyframe animation generated by the script

    cssAnimationName是脚本生成的关键帧动画的名称

  • fallbackFunction is the JavaScript function you wish to use in case the browser does not support CSS animation

    fallbackFunction是您希望在浏览器不支持CSS动画的情况下使用JavaScript函数

  • the script checks if the browser needs a vendor prefix for CSS animation (this is increasingly rare in modern browsers, thankfully)

    该脚本检查浏览器是否需要CSS动画的供应商前缀 (谢天谢地,在现代浏览器中这种情况越来越少)

The script creates an animation for each of the images and adds it in a stylesheet at the bottom of the page. An animation for four images with a duration of four seconds each, with a transition of two seconds, would generate the following:

该脚本为每个图像创建一个动画,并将其添加到页面底部的样式表中。 动画四张图像,每张图像的持续时间为四秒钟,过渡时间为两秒钟,将生成以下图像:

@keyframes fadey {
    0% { opacity: 1; }
    16.66% { opacity: 1; }
    25% { opacity: 0; }
    91.66% { opacity: 0; }
    100% { opacity: 1; }
}

Each image in the container is directed to the same animation:

容器中的每个图像都指向相同的动画:

#fadey img {
    position: absolute; top: 0;
    animation: fadey 24s ease-in-out infinite;
}

The container is sized with padding-top as percentage value, since the absolute positioning of the images will not contribute to the height of the container. The percentage amount is determined by finding the first loaded image in the container and dividing its width by its height:

由于图像的绝对位置不会影响容器的高度,因此将容器的大小设置padding-top为百分比值。 通过找到容器中的第一个加载图像并将其宽度除以其高度来确定百分比量:

imgAspectRatio = firstImage.naturalHeight / (firstImage.naturalWidth / 100)

The total duration of the animation is equal to the total number of images × (presentationTime + transitionTime)

动画的总持续时间等于图像总数×( presentationTime + transitionTime )

Each of the images is provided with an animation-delay. The generated CSS counts backwards from the last image in the container element (one that, due to the absolute positioning, is at the top of the image stack) using nth-last-child. CSS produced for the example above would be:

每个图像都具有animation-delay 。 生成CSS使用nth-last-child从容器元素中的最后一张图像(由于绝对定位而位于图像堆栈的顶部 )开始向后计数。 为上面的示例生成CSS将是:

#fadey img:nth-last-child(1) { animation-delay: 0s; }
#fadey img:nth-last-child(2) { animation-delay: 6s; }
#fadey img:nth-last-child(3) { animation-delay: 12s; }
#fadey img:nth-last-child(4) { animation-delay: 18s; }

If you want to call the script using custom options on this markup:

如果要使用此标记上的自定义选项来调用脚本,请执行以下操作:

<figure id="gallery">
    …
</figure>

Use the following:

使用以下内容:

cssFadey({
    presentationTime: 3,
    durationTime: 2,
    fadeySelector: '#gallery',
    cssAnimationName: 'sequence'
});

I’ve also created a CodePen repo for comments and contributions.

我还创建了一个CodePen存储库以供发表评论和贡献。

The one downside of this technique is that there’s no immediate method of jumping manually from one image to another. To keep the efficiency of CSS animation, manual control will mean the use of Web Animation API, as I’ll show in the next article.

这种技术的一个缺点是没有立即手动从一个图像跳转到另一个图像的方法。 为了保持CSS动画的效率,手动控制将意味着使用Web动画API,这将在下一篇文章中显示。

翻译自: https://thenewcode.com/360/CSSFadey-An-Automated-Fade-In-Image-Gallery

淡入淡出轮播图自动

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值