0

値に基づいてこのjQuery関数を使用して、4つのdivを10秒間切り替えていa href idます。

タイマーは正常に動作し、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 に答える