对于我的幻灯片,图像应该在图像淡出后改变,但图像在图像改变之前改变了。换句话说,图像发生变化,然后淡出并淡入。我在图像源更改之前放置了 fadeOut
方法。
HTML
<div class="image-section">
<img src="img/seattleskyline.jpg" alt="Seattle Skyline" id="center-image" />
<div class="caption">I still have absolutely no idea what this building is</div>
<button id="sliderLeft"></button>
<button id="sliderRight"></button>
</div>
CSS
#center-image
{
width: 100%;
height: 480px;
}
.image-section
{
margin-left: auto;
margin-right: auto;
width: 75%;
position: relative;
text-align: center;
}
.image-section .caption
{
position: absolute;
bottom: 4px;
width: 100%;
text-align: center;
color: white;
background: #474747;
height: 50px;
line-height: 50px;
opacity: 0.8;
font-size: 20px;
}
.image-section #sliderLeft
{
position: absolute;
display: none;
width: 25px;
height: 100px;
top: 50%;
margin-bottom: 50px;
left: 0;
opacity: 0.7;
border: 0;
}
.image-section #sliderRight
{
position: absolute;
display: none;
width: 25px;
height: 100px;
top: 50%;
margin-bottom: 50px;
right: 0;
opacity: 0.7;
border: 0;
}
JS
var images = ["img/seattleskyline.jpg", "img/spaceneedle.jpg", "img/ferriswheel.jpg"]
var index = 0;
$(document).ready(function() {
$("#sliderRight").fadeIn(1000);
$("#sliderLeft").fadeIn(1000);
function changeImage()
{
index++;
if (index > images.length - 1)
{
index = 0;
}
var target = document.getElementById("center-image");
$("#center-image").fadeOut(1000)
target.src = images[index];
$("#center-image").fadeIn();
}
setInterval(changeImage, 4000);
});
最佳答案
如您所知,fadeOut
需要 1000 毫秒才能完成。 Javascript 不知道这一点,也不在乎,所以它开始淡出,然后立即更改图像(下一行代码)。幸运的是,jQuery 允许您在 fadeOut
上指定回调方法。试试这个版本的 changeImage()
:
function changeImage()
{
index++;
if (index > images.length - 1)
{
index = 0;
}
var target = document.getElementById("center-image");
$("#center-image").fadeOut(1000, function() {
target.src = images[index];
$("#center-image").fadeIn();
});
}
此代码未经测试,但它肯定会让您走上正轨。干杯!
关于javascript - JQuery slider 在淡出之前更改图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30418743/