如何解决jQuery幻灯片,其中URL在图像之间可变淡入淡出
我创建了一个基于jQuery的幻灯片,该幻灯片位于我的网页上的DIV中。唯一的问题是图像之间没有过渡效果,只有一个到另一个图像之间没有过渡效果,而第一个图像不会逐渐消失,而下一个则逐渐消失。
我想淡化这些图像。我的JS中缺少什么?
var urls = ['https://example.com/front.png','https://example.com/interior-scaled.jpeg'];
var count = 1;
$('.hero').css('background-image','url("' + urls[0] + '")');
setInterval(function() {
$('.hero').css('background-image','url("' + urls[count] + '")');
count == urls.length-1 ? count = 0 : count++;
},6000);
});
解决方法
如果您不反对使用jQuery幻灯片库,那么我建议您使用Ken Wheelers Slick轮播jQuery库。
- slick.min.css的最小尺寸
1.4 KB
- slick-theme.min.css最小尺寸
3.07 KB
(仅在您希望使用基本主题样式时使用) - slick.min.js的最小尺寸
51.9 KB
您在第一个评论中提到...
即使图像像旋转木马一样滑动也足够。
很好的Slick可以轻松实现这两者,还可以加载其他一些很酷的选项,事件回调和响应性断点设置。可以使用已经在使用的jQuery加快为项目创建滑动/渐变轮播的速度。
在下面的示例中,我以fade: false
模式提供了2张英雄幻灯片。
-
#Hero_1
幻灯片在图像可能已加载或尚未加载之前运行。 -
#Hero_2
使用$(window).on('load')
确保幻灯片放映前图像已加载
// our hero examples as constant variables
const hero_1 = $('#hero_1');
const hero_2 = $('#hero_2');
// our slide image urls in constant variable array
const slides = [
'https://concorddentalde.com/wp-content/uploads/2020/10/concord-dental-patient-exam-room.jpeg','https://concorddentalde.com/wp-content/uploads/2020/10/concord-dental-interior-scaled.jpeg','https://concorddentalde.com/wp-content/uploads/2020/10/concord-dental-front.png'
];
// for each of the slide images as key > url
$.each(slides,function(key,url) {
// append slide to hero carousel div
$('.carousel','.hero').append('<div class="slide" style="background-image:url(\'' + url + '\');"></div>');
});
// the below slick js should not run until the above each function has finished appending images in slides array
// slick hero carousel on init
$('.carousel',hero_1).on('init',function(slick) {
// add show class to hero div to animate height when slick init
$(hero_1).addClass('show');
// slick carousel options
}).slick({
slidesToShow: 1,slidesToScroll: 1,dots: false,arrows: false,fade: true,adaptiveHeight: false,autoplay: true,infinite: true,pauseOnFocus: false,pauseOnHover: false,autoplaySpeed: 4000,speed: 1000,draggable: false
});
// use this if you want all background images to load first
// tho may be slow to run depending on how many images and the image size you are loading
$(window).on('load',function() {
// slick on init
$('.carousel',hero_2).on('init',function(slick) {
// add show class to hero div to expand height
$(hero_2).addClass('show');
// slick options
}).slick({
slidesToShow: 1,draggable: false
});
});
.hero {
position: relative;
overflow: hidden;
background: rgba(0,.75);
min-height: 0;
height: 0;
transition: all 0.5s ease;
margin: 0 0 .5rem 0;
}
.hero.show {
min-height: 150px;
height: 150px;
/*
height:45%;
height:45vh;
min-height:400px;
*/
}
.hero .carousel {
position: absolute;
top: 0;
right: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 0.5s ease;
}
.hero .carousel.slick-initialized {
opacity: 1;
}
.hero .carousel .slick-list,.hero .carousel .slick-track {
height: 100% !important;
}
.hero .carousel .slide {
background-color: none;
background-repeat: no-repeat;
background-size: cover;
background-position: 50% 50%;
height: 100%;
}
.hero .overlay {
color: #fff;
position: relative;
text-align: center;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
text-shadow: 1px 1px 2px rgba(0,.75);
}
/* for demo styling purposes */
BODY {
font-family: helvetica;
}
H1 {
font-size: 2rem;
font-weight: 600;
margin: 0 0 .5rem 0;
}
P {
margin: 0 0 .5rem 0;
}
.lead {
font-size: 1.4rem;
margin: 0 0 .5rem 0;
}
.row {
margin: 0 -4px 0 -4px;
}
.col {
float: left;
width: calc(50% - 8px);
padding: 0 4px 0 4px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css" rel="stylesheet" />
<div class="row">
<div class="col">
<p>
<code><strong>#hero_1</strong><br/></code>
<code><small>Slick inits after each function is complete.</small></code>
</p>
<div id="hero_1" class="hero">
<div class="carousel"></div>
<div class="overlay">
<h1>Hero 1</h1>
<p class="lead">
Tooth Hurty
</p>
</div>
</div>
</div>
<div class="col">
<p>
<code><strong>#hero_2</strong></code><br/>
<code><small>Waits for all imgs to load before init slick.</small></code>
</p>
<div id="hero_2" class="hero">
<div class="carousel"></div>
<div class="overlay">
<h1>Hero 2</h1>
<p class="lead">
Tooth Hurty
</p>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js"></script>
这里与上面的代码相同,但是处于fade: false
模式下……
-
#Hero_1
幻灯片在图像可能已加载或尚未加载之前运行。 -
#Hero_2
使用$(window).on('load')
确保幻灯片放映前图像已加载
// our hero examples as constant variables
const hero_1 = $('#hero_1');
const hero_2 = $('#hero_2');
// our slide image urls in constant variable array
const slides = [
'https://concorddentalde.com/wp-content/uploads/2020/10/concord-dental-patient-exam-room.jpeg',fade: false,.75);
}
/* for demo styling purposes */
BODY {
font-family: helvetica;
}
H1 {
font-size: 2rem;
font-weight: 600;
margin: 0 0 .5rem 0;
}
P {
margin: 0 0 .5rem 0;
}
.lead {
font-size: 1.4rem;
margin: 0 0 .5rem 0;
}
.row {
margin: 0 -4px 0 -4px;
}
.col {
float: left;
width: calc(50% - 8px);
padding: 0 4px 0 4px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css" rel="stylesheet" />
<div class="row">
<div class="col">
<p>
<code><strong>#hero_1</strong><br/></code>
<code><small>Slick inits after each function is complete.</small></code>
</p>
<div id="hero_1" class="hero">
<div class="carousel"></div>
<div class="overlay">
<h1>Hero 1</h1>
<p class="lead">
Tooth Hurty
</p>
</div>
</div>
</div>
<div class="col">
<p>
<code><strong>#hero_2</strong></code><br/>
<code><small>Waits for all imgs to load before init slick.</small></code>
</p>
<div id="hero_2" class="hero">
<div class="carousel"></div>
<div class="overlay">
<h1>Hero 2</h1>
<p class="lead">
Tooth Hurty
</p>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js"></script>
,
您可以使用transition: background-image
。并非所有浏览器都支持它,但是大多数现代浏览器都可以。
添加
-webkit-transition: background-image 0.5s ease-in-out;
transition: background-image 0.5s ease-in-out;
到具有背景图像的div的css。
这是一个带有示例的分叉小提琴:https://jsfiddle.net/bmh2qu0e/1/
,您可以在opacity
上使用过渡效果,并在背景变化时切换不透明度,例如:
$(document).ready(function() {
var urls = ['https://concorddentalde.com/wp-content/uploads/2020/10/concord-dental-patient-exam-room.jpeg','https://concorddentalde.com/wp-content/uploads/2020/10/concord-dental-front.png'
];
var count = 1;
var $hero = $('.hero');
$hero.css('background-image','url("' + urls[0] + '")');
setInterval(function() {
setTimeout(function() {
$hero.toggleClass('transparent');
setTimeout(function() {
$hero.css('background-image','url("' + urls[count] + '")');
count == urls.length - 1 ? count = 0 : count++;
$hero.toggleClass('transparent');
},300);
},300);
},6000);
});
.transparent {
opacity: 0;
}
.hero {
height: 45%;
height: 45vh;
min-height: 400px;
background-color: none;
text-align: center;
background-repeat: no-repeat;
background-size: cover;
background-position: 50% 50%;
-webkit-transition: opacity 0.5s ease-in-out;
transition: opacity 0.5s ease-in-out;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="hero"></div>
如果您想更进一步,可以使用class使它更通用:
class ImageSlider {
imagePos = 0;
intevalHandle = null;
intervalMS = 6000;
constructor(elem,images,startImmediately) {
this.images = images || [];
this.elem = $(elem);
if (startImmediately) {
this.startSlider();
}
}
startSlider() {
if (this.startTimer()) {
this.imagePos = 0;
this.onTimerInterval();
}
};
pauseSlider() {
this.clearTimer();
}
resumeSlider() {
this.startTimer();
}
stopSlider() {
this.clearTimer();
this.imagePos = 0;
};
startTimer() {
if (this.intervalHandle != null) {
return false;
}
this.intervalHandle = setInterval(() => this.onTimerInterval(),this.intervalMS);
return true;
};
clearTimer() {
if (this.intervalHandle) {
this.clearInterval(this.intervalHandle);
this.intervalHandle = null;
}
}
onTimerInterval() {
if (this.images.length <= 0) {
return;
}
setTimeout(() => {
this.elem.toggleClass('transparent');
setTimeout(() => {
if (this.imagePos >= this.images.length) {
this.imagePos = 0;
}
this.elem.css('background-image','url("' + this.images[this.imagePos] + '")');
this.imagePos++;
this.elem.toggleClass('transparent');
},300);
}
}
$(document).ready(function() {
var urls = ['https://concorddentalde.com/wp-content/uploads/2020/10/concord-dental-patient-exam-room.jpeg','https://concorddentalde.com/wp-content/uploads/2020/10/concord-dental-front.png'
];
var slider1 = new ImageSlider('#ss1',urls,true);
var slider2 = new ImageSlider('#ss2',[...urls].reverse(),true);
});
.transparent {
opacity: 0;
}
.hero {
height: 45%;
height: 45vh;
min-height: 400px;
background-color: none;
text-align: center;
background-repeat: no-repeat;
background-size: cover;
background-position: 50% 50%;
-webkit-transition: opacity 0.5s ease-in-out;
transition: opacity 0.5s ease-in-out;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="ss1" class="hero"></div>
<div id="ss2" class="hero"></div>
,
您不能使用CSS淡化单个背景图像。
可能的解决方案是在英雄<div>
内有两个容器。
例如:
<div class="hero">
<div class="img-container" id="first"></div>
<div class="img-container" id="second"></div>
</div>
为了获得理想的交叉淡入淡出效果,您将需要这些图像覆盖英雄<div>
上方的所需区域。
这可以通过以下CSS规则完成:
.img-container {
background-repeat: no-repeat;
background-size: cover;
background-position: 50% 50%;
background-color: transparent;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
现在,我们需要加载图像并相互淡入淡出。
$(document).ready(function() {
var urls = [
'imgURL1','imgURL2','imgURL3'
];
// Preload the images
var tempImg = []
for (var i = 0; i < urls.length; i++) {
(new Image()).src = urls[i]
}
// The currently shown image's index
var currentShown = 0;
// Get the containers
var first = $("#first");
var second = $("#second");
// This shows whether the second object is on top or not
var secondOnTop = true;
// Set the first container's value so that there is something on the screen and load the second image on top.
first.css('background-image','url("' + urls[urls.length - 1] + '")');
second.css({
backgroundImage: 'url("' + urls[0] + '")',opacity: 1
});
// Change the image every X seconds
setInterval(function() {
var animationSpeed = 1000; // In milliseconds
// Increment currently shown image index
currentShown === urls.length - 1 ? currentShown = 0 : currentShown++;
// Determine which object has visual priority
var primaryObj = first;
var auxObj = second;
if (secondOnTop) {
primaryObj = second;
auxObj = first;
}
secondOnTop = !secondOnTop;
// Show aux obj background
auxObj.css({backgroundImage: 'url("' + urls[currentShown] + '")'});
auxObj.animate({
opacity: 1
},animationSpeed);
// Change shown object's background and set to 0
primaryObj.animate({
opacity: 0,},animationSpeed,function() {
// Change the primary's background to the next in queue
var nextImg = currentShown === urls.length - 1 ? 0 : currentShown + 1;
primaryObj.css('background-image','url("' + urls[nextImg] + '")');
});
},6000);
});
我在这里创建了一个小提琴的叉子: https://jsfiddle.net/YeloPartyHat/uLfr389g/88/
,这是一个解决方案:(我必须将短网址替换为完整网址,否则将无法让我保存答案)
$(document).ready(function(){
var urls = ['https://concorddentalde.com/wp-content/uploads/2020/10/concord-dental-patient-exam-room.jpeg','https://concorddentalde.com/wp-content/uploads/2020/10/concord-dental-front.png'];
var totalLayers = 2;
var layerIndex = 0;
var count = 0;
$('.layer-' + layerIndex)
.removeClass('layer')
.css('background-image','url("' + urls[count] + '")');
console.log({first: layerIndex,second: (layerIndex + 1) % totalLayers,count})
setInterval(function() {
var outLayer = layerIndex
var inLayer = ++layerIndex % totalLayers
layerIndex = inLayer
count = ++count % urls.length;
console.log({first: outLayer,second: inLayer,count})
$('.layer-' + outLayer)
.addClass('animateXFadeOut');
$('.layer-' + inLayer)
.removeClass('layer')
.css('background-image','url("' + urls[count] + '")')
.addClass('animateXFadeIn');
setTimeout(function() {
$('.layer-' + outLayer).css({backgroundImage: 'none',opacity: 1});
$('.layers').removeClass('animateXFadeIn animateXFadeOut');
},1000);
},6000);
});
.hero {
/* height: 45%;
height: 45vh;
min-height: 400px;
*/
background-color: none;
text-align: center;
background-repeat: no-repeat;
background-size: cover;
background-position: 50% 50%;
}
@keyframes xfadein {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes xfadeout {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
.animateXFadeIn {
animation-name: xfadein;
animation-duration: 1s;
}
.animateXFadeOut {
animation-name: xfadeout;
animation-duration: 1s;
}
.layer-0,.layer-1 {
display: block;
position: absolute;
height: 45%;
height: 45vh;
min-height: 400px;
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="hero">
<div class="layers layer-0"></div>
<div class="layers layer-1"></div>
</div>
,
您可以使用一个小类和一行jquery来做到这一点
$(document).ready(function(){
var urls = ['image_one_url','image_two_url','image_three_url'];
var count = 1;
$('.hero').css('background-image','url("' + urls[0] + '")');
$('.hero').addClass('animatedinout');
setInterval(function() {
$('.hero').css('background-image','url("' + urls[count] + '")');
count == urls.length-1 ? count = 0 : count++;
},6000);
});
.animatedinout{
animation: fadeinout;
animation-duration: 6000ms;
animation-timing-function: ease-in-out;
animation-iteration-count: infinite;
}
@keyframes fadeinout{
0%{
opacity: 0;
}
10%{
opacity: 1;
}
90%{
opacity: 1;
}
100%{
opacity: 0;
}
}
我只需添加一个名为css
的{{1}}类,就可以每6000毫秒永远使用一次动画并添加
animatedinout
在setInterval之前。
,我感谢大家的辛勤工作。我发现的解决方案(因为我的期限很紧)实际上很简单,并且结合了JS和CSS来实现“真正的”交叉淡入淡出过渡。
HTML:
<div id="background-images">
<div class="bgImages active" id="bgImg1"></div>
<div class="bgImages" id="bgImg2"><br></div>
<div class="bgImages" id="bgImg3"><br><br></div>
<div class="bgImages" id="bgImg4"><br></div>
<div class="bgImages" id="bgImg5"><br><br></div>
</div>
jQuery:
function cycleImages() {
var $active = $("#background-images .active");
var $next = $active.next().length > 0
? $active.next()
: $("#background-images div:first");
$next.css("z-index",2); // move the next img up the stack
$active.fadeOut(1500,function() {
//fade out the top image
$active.css("z-index",1).show().removeClass("active"); //reset z-index and unhide the image
$next.css("z-index",3).addClass("active"); //make the next image the top one
});
}
$(document).ready(function() {
$("#cycler img").show();
// run every 6 seconds
setInterval(cycleImages,6000);
});
CSS:
#background-images {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 670px;
z-index: -5;
}
#bgImg1,#bgImg2,#bgImg3,#bgImg4,#bgImg5 {
width: 100%;
height: 100%;
position: fixed;
background-position-x: center;
background-position-y: center;
background-size: cover;
background-repeat: no-repeat;
}
#bgImg1 { background-image: url("https://image1.jpg"); }
#bgImg2 { background-image: url("https://image2.png"); z-index: 2; }
#bgImg3 { background-image: url("https://image3.jpeg"); }
#bgImg4 { background-image: url("https://image4.jpg"); }
#bgImg5 { background-image: url("https://image5.jpeg"); }
这是一种结合使用z-index和有效状态来使图像真正淡化而没有白色“闪烁”的聪明方法。
在CodePen here上找到它。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。