循环图像并停止悬停 - jQuery

时间:2014-02-04 17:38:28

标签: javascript jquery html css

我试图创建一个图像循环,当您将鼠标悬停在链接上时,它会明智地显示相关图像,因此,例如,如果您将鼠标悬停在第4个链接上,则当您悬停时,第4个图像显示并且循环停止在没有任何链接或鼠标离开的情况下,循环再次开始。

我做了一个简单的小提琴试图解释我的想法只是我无法弄明白。任何帮助表示赞赏。

http://jsfiddle.net/Q4ajK/3

的jQuery

$('#vennD li:gt(0)').hide();

intervalId = setInterval(function() {
 $("#vennD li:first-child").fadeOut(500).next("li").fadeIn(500).end().appendTo("#vennD")
}, 1000);


$( '.targ' ).hover(function() {

    var tabIndex = $(this).index();

    $('#vennD li').hide();


    $('#vennD li').eq(tabIndex).addClass("show").show();

    clearInterval(intervalId);

}, function() {

    $('#vennD li').removeClass("show");

    intervalId = setInterval(function() {
 $("#vennD li:first-child").fadeOut(500).next("li").fadeIn(500).end().appendTo("#vennD")
}, 1000);

}); 

2 个答案:

答案 0 :(得分:1)

您的代码中的问题是您实际上移动 <li>内的<ul>

因此,当您悬停第一个链接时,第一个<li>不一定是相应的链接。

我已经在你的jsFiddle上更新了代码(+添加了一些颜色......:D),你可以在这里查看我的解决方案:http://jsfiddle.net/Q4ajK/4/

以下是完整代码:

<强> HTML

<ul id="vennD">
    <li><img src="http://www.placehold.it/100x100/D00" /></li>
    <li><img src="http://www.placehold.it/100x100/0D0" /></li>
    <li><img src="http://www.placehold.it/100x100/00D" /></li>
    <li><img src="http://www.placehold.it/100x100/0DD" /></li>
    <li><img src="http://www.placehold.it/100x100/DD0" /></li>
</ul>
<div>
    <a href="#" class="targ" style="color: #D00">link</a>
    <a href="#" class="targ" style="color: #0D0">link</a>
    <a href="#" class="targ" style="color: #00D">link</a>
    <a href="#" class="targ" style="color: #0DD">link</a>
    <a href="#" class="targ" style="color: #DD0">link</a>
</div>

<强>的Javascript

// Initialization
$('#vennD li:first').addClass('show');
$('#vennD li:gt(0)').hide();

function loopImages() {
    // Retrieve the currently shown <li>, try to find the next <li>
    var next = $("#vennD li.show").next('li');
    // If not foudn, then retrieve the first one in the list
    if (!next.length) next = $("#vennD li:first");
    // Remove ".show", and hide the current <li>
    $("#vennD li.show").removeClass('show').fadeOut(500);
    // Add ".show" and show next <li>
    next.addClass('show').fadeIn(500);
}

intervalId = setInterval(loopImages, 1000);

$('.targ').hover(function () {
    clearInterval(intervalId);
    var tabIndex = $(this).index();
    // Hide & remove ".show"
    $('#vennD li').hide().removeClass('show');
    // Add ".show" & display targeted <li>
    $('#vennD li').eq(tabIndex).addClass("show").show();
}, function () {
    intervalId = setInterval(loopImages, 1000);
});

答案 1 :(得分:0)

除了调用clearInterval(intervalId)之外,您还需要释放变量并检查每个悬停函数中是否存在该变量。例如,在hover下的第一个函数中,您将添加:

    if(!intervalId){
        return;
    }

然后在intervalId = null;

之后添加clearInterval(intervalId);

在第二个函数中,您只需要添加:

    if(intervalId){
        return;
    }

And here's the JSFiddle显示了这一点。

有关详情,我使用Stopping jQuery cycle function on hover作为来源。

相关问题