0

我有一个画廊网站,它创建一串缩略图,然后显示更大版本的缩略图并每 4 秒循环到下一个。我写了一个点击函数,这样用户就可以通过点击缩略图来选择一个特定的图像。大的“显示”图像将立即转换为用户单击的图像,并且计时器将被重置。当我尝试实现一个在用户将鼠标悬停在“显示”图像上时暂停幻灯片放映然后在 mouseLeave 上重置计时器的功能时遇到了一些麻烦。我终于让它工作了,但是现在在用户单击链接以加载不同的画廊后,我选择特定图像的单击功能不再起作用(总共有五个可供选择)。它适用于页面刷新,但是一旦选择了单独的画廊并且拇指加载它不再起作用。下面是我的幻灯片放映的 jQuery 代码。我在想,也许我在某个地方错过了一个代表团,或者我的职能组织不正确。

$(document).ready(function(){

var timer = play()

function play() {
    i = setInterval(advanceImage, 4000);
    return i;
}

function pause() {
    clearInterval(timer)
}

var gallery = drawings;



//Creates array variable based on what user clicks
$('.nav li a').click(function() {
    $('#thumbs').children().remove();
    gallery = window[this.id];
    $.each(gallery, function(index, value){
        $('#thumbs').append('<img src="'+value+'" />');
    });
    return;
});

//Adding images to thumbs
$.each(gallery, function(index, value){
    $('#thumbs').append('<img src="'+value+'" />');
});

//Creates a current image from array
function currentImage(){
    i = jQuery.inArray($('#current-img').attr('src'), gallery);
    return i;
}

//Cycles through array
function advanceImage(){
    currentImage();
    if (i < gallery.length - 1){
        changeImage(i + 1);
    }else{
        changeImage(0)
    }
}

//Change current image to whatever i gives it
function changeImage(i){
    $('#current-img').stop().animate({
        opacity: 0,
    }, 200, function(){
        $('#current-img').attr('src', gallery[i]);
        $('#slideshow-container img').load(function(){
            $('#current-img').stop().animate({
                opacity: 1,
            }, 200)
        })
    })
}

//Clicking thumbnail function
$('#thumbs img').click(function(){
    var newImage = $(this).attr('src');
    $.each(gallery, function(index, value){
        if (value == newImage){
            changeImage(index);
        };
    });
    clearInterval();
});



//Stop rotation on hover
$('#current-img').mouseenter(function() {
    pause();
})
$('#current-img').mouseleave(resetInterval);
    function resetInterval() {
        timer = play();
    }
4

1 回答 1

0

在 DOM 已加载后添加图像。因此,您的点击功能不会附加到您的任何图像(这就是它不起作用的原因)。您需要将事件处理程序附加到文档,以便它处理在 DOM 加载后创建的图像。

改变这个:

//Clicking thumbnail function
$('#thumbs img').click(function(){
    var newImage = $(this).attr('src');
    $.each(gallery, function(index, value){
        if (value == newImage){
            changeImage(index);
        };
    });
    clearInterval();
});

对此:

//Clicking thumbnail function
$(document).on('click', '#thumbs img', function(){
    var newImage = $(this).attr('src');
    $.each(gallery, function(index, value){
        if (value == newImage){
            changeImage(index);
        };
    });
    clearInterval();
});

演示 1 - 请注意,在此演示中,您可以通过单击删除添加的图像。

演示 2 - 请注意,在此演示中,您无法删除添加的图像,因为使用.click而不是.on.

于 2013-09-13T20:01:07.940 回答