简体   繁体   English

如何在JQuery中滚动浏览元素?

[英]How can I scroll through elements in JQuery?

Roughly, I'd trying to make a series of buttons ABCD, where clicking on A scrolls you to B, clicking on B scrolls you to C, etc, and clicking on D scrolls you to A. 粗略地讲,我试图制作一系列按钮ABCD,其中单击A将您滚动到B,单击B将您滚动到C,依此类推,然后单击D将您滚动到A。

I have buttons ("tags") that all have the class tag and a specific tag, like green . 我有所有具有类tag和特定标签(如green )的按钮(“标签”)。 I'm trying to make it so that clicking on a tag called "green" takes you to the next "green," unless it's the last one, in which case it starts over. 我正在努力做到这一点,以便单击名为“绿色”的标签将您带到下一个“绿色”,除非它是最后一个,否则它将重新开始。

Here's what I've been trying: 这是我一直在尝试的方法:

$(document).ready(function(){
    counter = 0
    $('.tag').click(function(){
        counter = counter + 1; 
        var scrollTo = '.' + $(this).text(); 
        scrollTo = $(scrollTo)      
        console.debug(scrollTo);
        len = scrollTo.length
        if ( counter > len-1 ) { 
            counter = 0; 
            scrollTo = $(scrollTo)[0]; 
        } else { 
            scrollTo = $(scrollTo)[counter]
        } 
        console.debug(scrollTo);
        $('html, body').animate({ scrollTop: $(scrollTo).parent().offset().top });
    }); 
}); 

This mostly works, but only if you start at the beginning. 这通常有效,但前提是您从头开始。 I'm trying to make it so that clicking on the 2nd "green" tag, it takes you to the 3rd, etc. 我试图做到这一点,以便单击第二个“绿色”标签,将您带到第三个,依此类推。

I know I'm making this unnecessarily convoluted. 我知道我正在对此进行不必要的混淆。 Is there an easier way? 有更容易的方法吗?

You can use this code to find index of current element: 您可以使用以下代码查找当前元素的索引:

    var counter = 0; 
    var scrollToSelector = '.' + $(this).text(); 
    var scrollTo = $(scrollToSelector);
    var self = this;
    scrollTo.each(function(i, e){
        if (e == self) {
            counter = i + 1;
        }
    });
    if (counter >= scrollTo.length) {
        counter = 0;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM