我的自定义jQuery滑块发生了奇怪的事情

时间:2014-09-14 21:51:21

标签: javascript jquery html arrays logic

我正在设置一个非常简单的jQuery滑块,当点击箭头(右或左)时,该滑块将淡入3段文本。我遇到的问题是在段落中循环,它没有正确递增。在第一个箭头单击时,它会跳到第三个段落。然后在另一次点击后重复第三段。

这是一个jsfiddle:http://jsfiddle.net/j0h2qy0z/

基本HTML是:

<div class="textSlider">
    <div class="sliderArrow arrowLeft"><span><</span></div>

    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <p>Paragraph 3</p>

    <div class="sliderArrow arrowRight"><span>></span></div>
</div>

jQuery将每个段落的内容存储在一个数组中

var paragraphs = [];

$('p', '.textSlider').each(function() {
    var content = $(this).html();
    paragraphs.push(content)
});

并隐藏所有段落,但第一个

$('p', '.textSlider').first().siblings('p').hide();

我试图在jsfiddle中给出好的评论,所以这可能是查看正在发生的事情的最佳方式,但似乎问题很可能出现在这段代码中,但我似乎无法弄清楚发生了什么:

if (currentParagraph < numParagraphs && currentParagraph >= 0) {
     currentParagraph += direction;   
} else if (currentParagraph < 0) {
    currentParagraph = numParagraphs;
} else {
    currentParagraph = 0;
};

提前致谢!

1 个答案:

答案 0 :(得分:0)

我希望你不要介意,但我改变了一些事情(在我看来更容易理解):

HTML:

<table align="center">
    <tr>
        <th id="backward"><span><<</span></th>
        <td class="slide-head">Paragraph 1</td>
        <td class="slide-head hidden">Paragraph 2</td>
        <td class="slide-head hidden">Paragraph 3</td>
        <!-- ... -->
        <th id="forward"><span>>></span></th>
    </tr>
</table>
<p class="content" align="center">Paragraph 1 content</p>
<div class="paragraphs hidden">Paragraph 1 content</div>
<div class="paragraphs hidden">Paragraph 2 content</div>
<div class="paragraphs hidden">Paragraph 3 content</div>
<!-- ... -->

CSS:

.hidden {
    display:none;
}

table td {
    padding:0px 80px 0px 80px;
}

#forward span, #backward span {
    background-color:green;
    padding: 0px 5px 0px 5px;
}

#forward:hover span, #backward:hover span {
    font-size:17px;
}

#forward:active span, #backward:active span {
    font-size:16px;
}

的Javascript:

$(function() {
    var headers    = (a) => $(".slide-head:eq(" + a + ")"),
        content    = $(".content"),
        paragraphs = (a) => $(".paragraphs:eq(" + a + ")"),
        curIndex   = 0;

    $("#backward, #forward").click(function() {
        headers(curIndex).addClass('hidden');
        if ($(this).attr("id") === "backward") {
            curIndex = (curIndex > 0) ? curIndex - 1 : $('.slide-head').length - 1;
        } else {
            curIndex = (curIndex < $('.slide-head').length - 1) ? curIndex + 1 : 0;
        }
        headers(curIndex).removeClass('hidden');
        content.text(paragraphs(curIndex).text());
    });
});

这是 fiddle