javascript - JQuery slider 在淡出之前更改图像

标签 javascript jquery html css

对于我的幻灯片,图像应该在图像淡出后改变,但图像在图像改变之前改变了。换句话说,图像发生变化,然后淡出并淡入。我在图像源更改之前放置了 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/

相关文章:

php - 未捕获的语法错误 : Unexpected token in Wordpress button function

php - json_encode 和重音

javascript - 使用 jQuery 更改 jQuery Mobile "select"的高度?

python - Beautifulsoup 带有下拉菜单的网页抓取网站

javascript - 使用 html5 验证电子邮件

javascript - 如何 "mount"Angular 2 模块在路由层次结构中某个点的路由

javascript - 无法访问被点击的元素

javascript - 什么是AJAX,它如何工作?

javascript - 问题将 MVC 中的模型对象获取到 jQuery 变量

javascript - 如何在 Javascript 中获取当前目录名称?