在幻灯片中添加“后退”和“前进”功能

18

我用 PHP 和 JavaScript 制作了一个幻灯片,它可以正常滑动图片,但是在前进和后退功能上有些卡住了,如果你能帮我一下,我将不胜感激。以下是我目前所做的:

PHP:

$dir = 'images/slideshow';
$images = scandir($dir);
$i = 0;

echo '<div id="slideshow-wrapper">';    
echo '<div id="slideshow-beta">';

foreach($images as $img){
    if ($img != '.' && $img != '..') {
        $i++;
        echo '<img src="../images/slideshow/'.$img.'" class="img_'.$i.'">';
    }
}

echo '</div>';
echo '<div id="slideshow-controller">'; 
echo '<div class="left-arrow-div"><span class="left-arrow"  onclick="SlideShow(-1);"></span></div>';
echo '<div class="right-arrow-div"><span class="right-arrow"  onclick="SlideShow(1);"></span></div>';
echo '</div>';
echo '</div>';

Javascript:

var i=1;
var begin=true;
function SlideShow(x){
    if(x==-1){
        i--;
    }else if(x==1){
        i++;
    }
    var total=$('#slideshow-beta img').length;

        for(var j=1;j<=total;j++){
            if($('.img_'+j).css('display')!='none'){
                begin=false;
                break;
            }else{
                begin=true;
            }
        }

        if(i>total){
            i=1;
            $('.img_'+total).fadeOut(1000,function(){
                $('.img_'+i).fadeIn(1000);
            });
        }else if(begin){
            $('.img_'+i).show();

        }else if(!begin){

            $('.img_'+(i-1)).fadeOut(1000,function(){
                $('.img_'+i).fadeIn(1000);
            });
        }

        setTimeout(function(){
            i++;            
            SlideShow(x);
        },5000);

}

HTML:

<body onload="SlideShow(false);">

你可以看到我尝试创建一个onclick事件在运行时改变'i'的值,虽然值已经改变了,但是图片没有改变。可能是因为点击后退/前进会调用另一个函数实例而不是覆盖它。我不确定,我对这个问题感到困惑。

这里有一个演示


3
如果你在JSFiddle上分享你的代码并且不包含PHP,问题将会很快得到解决。 - Sherali Turdiyev
1
同时,将 if(i==total+1){ 改为 if(i>total){ - Sherali Turdiyev
2
StackOverflow也支持fiddles。 - viral
2
我会回来的,带着小提琴。 - Petru Lebada
1
替换以下代码:else if(!begin){else { - Sherali Turdiyev
显示剩余7条评论
5个回答

7
我徹底改造了它,但是核心思想沒有改變(範例):
CSS的更改如下:
.left-arrow, .right-arrow {
    cursor: pointer;
    /** display: none **/
}

#slideshow-controller {
    z-index: 2;
    position: absolute;
    /** added **/
    opacity: 0;
    transition: opacity 300ms ease-in;
    /***********/
}
#slideshow-wrapper:hover > #slideshow-controller {
    opacity: 1;
}

HTML的更改(移除内联onClick):

<div class="left-arrow-div"><span class="left-arrow">Back</span>

</div>
<div class="right-arrow-div"><span class="right-arrow">Forward</span>

</div>

Javascript:

var i = 0;
var images = $('#slideshow-beta img'); // cache all images
var total = images.length;
var timeout;

/*** hide all images at the start ***/
images.each(function (index) {
    $(this).css({
        display: 'none'
    });
});

/*** bind event handlers to arrows ***/
$('.left-arrow').click(function () {
    SlideShow(-1);
});

$('.right-arrow').click(function () {
    SlideShow(1);
});

/*** Start the slideshow on 1st image ***/
SlideShow(0);


function SlideShow(x) {
    if (isNaN(x)) { // throw error if x is not a number
        throw new Error("x must be a number");
    }

    clearTimeout(timeout); // clear previous timeout if any to prevent multiple timeouts running

    var current = (total + i + x % total) % total; // get the current image index

    $(images[i]).fadeOut(1000, function () { // fade out the previous
        $(images[current]).fadeIn(1000); // fade in the current
    });

    i = current; // set i to be the current

    timeout = setTimeout(function () { // cache the timeout identifier so we can clean it
        SlideShow(1);
    }, 5000);

}

厉害的算法,'(total + i + x % total) % total',正是我正在寻找的关键,非常感谢。 - Petru Lebada
1
欢迎。这是手工制作的 :-P - Ori Drori

4
我已经解决了你的问题 - 主要问题是你调用了内联函数,但是在页面加载时该函数并不存在(以毫秒计算)。另一个问题是你的if语句(现在是3)包括类型 - 因为false、0、-1等都是“相同的”。 现在唯一的问题是间隔无限运行,并且可以在手动更改后立即调用下一个图像。
总之,我建议你使用类似cycle2或类似的库。

https://jsfiddle.net/Lroatbzg/15/

jQuery(window).on('load', function() {
    $("#slideshow-wrapper").hover(function(){
       $(".left-arrow,.right-arrow").fadeIn();
    }, function(){
         $(".left-arrow,.right-arrow").fadeOut();
    });
    var i=1;
    var total = $('#slideshow-beta img').length;
    function SlideShow(x) {
        if(x === -1) {
            i--;
        } else if(x === 1) {
            i++;
        }

        if(i > total) {
            i = 1;
        }

        $('#slideshow-beta img').hide();
        $('#slideshow-beta .img_' + i).fadeIn(1000);
    }

    setInterval(function() {
        i++;
        SlideShow(i);
    }, 5000);

    jQuery('.left-arrow-div').on('click', function() {
        SlideShow(-1);
    });

    jQuery('.right-arrow-div').on('click', function() {
        SlideShow(1);
    });

    SlideShow(false);
});

谢谢你的回答,但我不想使用任何库,这段代码完全是我自己写的,我想保持它的原样,尽管我需要一些帮助... - Petru Lebada
我建议您编写一个对象,可能是一个jQuery扩展,并在其中添加函数,例如:“SlideShow.next()”,并在该对象中处理所有事情,不要让任何人更改您的内部内容。 - Gummibeer

0
你的代码出现了一个“ReferenceError: SlideShow is not defined”错误(在Firefox中使用Firebug调试)。
尝试将function SlideShow(x){...}替换为SlideShow = function (x) {...}https://jsfiddle.net/Lroatbzg/12/)。
老实说,我不知道为什么后者能够工作,因为对我来说这两个语句是等价的(对此有什么解释吗?)。
以另一种方式声明函数可以消除错误 - 至少在我的浏览器中是这样。

到目前为止,没有人抱怨过这样的问题,我也没有遇到过这个错误。 - Petru Lebada
你的代码是否出现错误或者点击事件没有任何反应?你是否使用调试器(如Firebug)? - PinkTurtle
我的代码运行良好,没有错误,我只需要一些帮助来实现一些功能,请重新阅读问题。 - Petru Lebada

0

使用

if(x=='-1'){
    i--;
}else if(x=='1'){
    i++;
}

替代

if(x==-1){
    i--;
}else if(x==1){
    i++;
}

-1
问题在于setTimeOut将延迟执行SlideShow函数。但是,当您单击按钮时,此延迟执行不会停止。为了停止此执行,我对代码进行了小修改。此外,我通过jQuery启动了onClick功能来解决jsfiddle中的ReferenceError。
可以在此处检查此结果:https://jsfiddle.net/Lroatbzg/13/
$("#slideshow-wrapper").hover(function(){
   $(".left-arrow,.right-arrow").fadeIn();
}, function(){
     $(".left-arrow,.right-arrow").fadeOut();
});
    var i=1;
var direction=1;
var begin=true;
var latest=Math.random();
function SlideShow(parameter){
    if(latest!=parameter)
        return;  //Return when this function is not called through the last click or timeout.
    var total=$('#slideshow-beta img').length;
    i=i+direction;
    if(i>total)
        i=1;
    if(i<1)
        i=total;
    begin=true;
    for(var j=1;j<=total;j++)
    {
        if($('.img_'+j).css('display')!='none')
        {
            begin=false;
            $('.img_'+total).fadeOut(1000,function(){
                $('.img_'+j).css('display','none');
                $('.img_'+i).fadeIn(1000);
            });
            break;
        }
    }
    if(begin)
        $('.img_'+i).show();
    setTimeout(function(){
        SlideShow(parameter);
    },5000);
}
SlideShow(latest);
$("#left").click(function(){ latest=Math.random(); direction=-1; SlideShow(latest); });
$("#right").click(function(){ latest=Math.random(); direction=1; SlideShow(latest); });

HTML代码已更改如下:

<div id="slideshow-controller"> 
    <div class="left-arrow-div" id="left"><span class="left-arrow">Back</span></div>
    <div class="right-arrow-div" id="right"><span class="right-arrow">Forward</span></div>
</div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接