0

我使用这个基于a href id值的 jQuery 函数将每个 4 个 div 切换 10 秒。

计时器工作正常,它每 10 秒更改 4 个 div,但是当用户单击特定 div 时,它不会导航到特定 div 并停留在给定时间段(例如 10 秒)并从当前 div 进入下一个 div 而不是它根据计时器值进入 div。

任何人都可以帮我解决这个问题吗?

$(function() {
    $("a.menu").click(function() {
        $("div.featuredposts_content").hide();
        $($(this).attr('href')).show();
        return false;
    });
});

$(function() {
    var counter = 0,
        divs = $('#cat1, #cat2, #cat3,#cat4');

    function showDiv() {
        divs.hide() // hide all divs
        .filter(function(index) {
            return index == counter % 4;
        }) // figure out correct div to show
        .show('fast'); // and show it
        counter++;
    }; // function to loop through divs and show correct div
    showDiv(); // show first div    
    setInterval(function() {
        showDiv(); // show next div
    }, 15 * 1000); // do this every 10 seconds    
});​
4

1 回答 1

0

我假设评论中发布的片段的确切标记。

首先,我认为你应该在每个完整周期后重新设置你的计数器,否则它会增长,增长,增长并最终可能导致异常,可能不是在前 2-3 天内,而是最终。没有必要让counter变量超出divs.length.

除此之外,您的代码中唯一真正缺少的是点击事件中计数器值的设置:

$("a.menu").click(function() {
    $("div.featuredposts_content").hide();
    var $divToShow = $($(this).attr('href'));
    $divToShow.show();
    
    // save the index of the new div +1 to ensure it moves on to the div thereafter
    counter = divs.index($divToShow) + 1; 
    
    return false;
});

演示- 计时器从选定的 div 继续

(出于演示目的,我缩短了 DEMO 中的计时器,您当然应该将其重新设置为原始值)

我使用了以下假定的 HTML:

<a href="#cat1" class="menu">cat1</a>
<a href="#cat2" class="menu">cat2</a>
<a href="#cat3" class="menu">cat3</a>
<a href="#cat4" class="menu">cat4</a>
<div id="cat1" class="featuredposts_content">Category1</div>
<div id="cat2" class="featuredposts_content">Category2</div>
<div id="cat3" class="featuredposts_content">Category3</div>
<div id="cat4" class="featuredposts_content">Category4</div>

​ 这是完整的脚本:

$(function() {
    var counter = 0;
    var divs = $('#cat1, #cat2, #cat3, #cat4');

    function showDiv() {
        divs.hide() // hide all divs
        .filter(function(index) {
            return index == counter % divs.length;
        }) // figure out correct div to show
        .show('fast'); // and show it
        if(counter == divs.length){
            counter = 1;
        } else {
            counter++
        }
    }; // function to loop through divs and show correct div
    showDiv(); // show first div    
    setInterval(function() {
        showDiv(); // show next div
    }, 2000); // do this every 10 seconds    
    
    $("a.menu").click(function() {
        $("div.featuredposts_content").hide();
        var $divToShow = $($(this).attr('href'));
        $divToShow.show();
        
        counter = divs.index($divToShow) + 1;
        
        return false;
    });
});
于 2012-12-22T10:28:28.863 回答